UNION ALL Sql查询 - 如何绑定三个表

时间:2012-10-05 03:19:42

标签: sql db2 union union-all

我有以下表格:

T1

  ID  PRIORITY
  1      1
  2      1
  3      2
  4      4

T2

ID  SERVICE
1   PSTN
1   ADSL
3   ADSL

T3

ID   DEVICE
1    BSC1
3    BSC7 
4    BSC7

我想作为输出

ID  PRIORITY SERVICE/DEVICE
1      1        PSTN
1      1        ADSL
1      1        BSC1
2      1
3      2        ADSL
3      2        BSC7

如何使用UNION ALL绑定这些表?我还必须为T1 WHERE PRIORITY!=4

添加WHERE子句

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

谢谢

2 个答案:

答案 0 :(得分:3)

如果你只使用UNION而不是UNION ALL,那么这应该可以提供你想要的东西

SELECT t1.Id, t1.Priority, COALESCE(t2.Service, '') AS [Service/Device]
FROM t1
LEFT JOIN t2 ON t1.Id = t2.Id
WHERE t1.Priority != 4

UNION 

SELECT t1.Id, t1.Priority, COALESCE(t3.Device, '') AS [Service/Device]
FROM t1
LEFT JOIN t3 ON t1.Id = t3.Id
WHERE t1.Priority != 4

SQL Fiddle example

答案 1 :(得分:1)

select T1.id , T1.PRIORITY ,T2.SERVICE  as service/Device from  t1 
left outer join T2 on T2.id=T1.id where T1.PRIORITY!=4
union all
select T1.id , T1.PRIORITY ,T3.DEVICE as service/Device from  t1 
left outer join T3 on T3.id=T1.id where PRIORITY!=4