4

我有以下表格:

T1

  ID 
  1
  2
  3

T2

ID  SERVICE
1   PSTN
1   ADSL
3   ADSL

T3

ID   DEV
1    3G
3    2G 

我想作为输出

ID  SERVICE/DEV
1      PSTN
1      ADSL
1      3G
2
3      ADSL
3     2G

这个怎么合并?

我不能用经典LEFT OUTER JOIN

一个 id 的输出表中的总数应该是摘要,T2+T3 (FOR ID=1 2+1=3)ID=2它也应该存在于表输出中,第二列为空白。

4

3 回答 3

7

您可以简单地将两个表的结果专门组合在一起,T2并在子查询中T3使用,然后将其与using连接起来。尝试这个,unionT1LEFT JOIN

SELECT t1.ID, b.Service
FROM T1 LEFT JOIN
    (
        SELECT ID, Service FROM T2
        UNION ALL
        SELECT ID, Dev AS Service FROM T3
    ) b ON t1.ID = b.ID

此外,COALESCE如果要自定义具有null值的列,则可以使用。所以在下面的例子中,由于2没有service,它将显示-none-而不是null

SELECT t1.ID, COALESCE(b.Service, '-none-') Service
FROM T1 LEFT JOIN
    (
        SELECT ID, Service FROM T2
        UNION ALL
        SELECT ID, Dev AS Service FROM T3
    ) b ON t1.ID = b.ID

请参阅 SQLFiddle 演示

于 2012-10-03T13:48:43.643 回答
2

你可以试试这个。

SELECT T1.ID, service "SERVICE/DEV"
FROM T1, T2
WHERE T1.ID = T2.ID(+)
UNION
SELECT T1.ID, dev "service/dev"
FROM T1, T3 
WHERE T1.ID = T3.ID(+);
于 2012-10-03T13:54:22.490 回答
1

你想要联合/联合吗?

select *
from ((select id, service
       from t2
      ) union all
      (select id, service
       from t3
      ) union all
      (select id, NULL as service
       from t1
       where t1.id not in (select id from t2) and
             t1.id not in (select id from t3)
      )
     ) t

NOT INinWHERE子句可能不是最有效的方法。但这就是你想要的结果吗?

于 2012-10-03T13:47:47.527 回答