[英]SQL query merge two columns from two tables in one column of resulting table?
I have the following tables: 我有以下表格:
T1 T1
ID
1
2
3
T2 T2
ID SERVICE
1 PSTN
1 ADSL
3 ADSL
T3 T3
ID DEV
1 3G
3 2G
I want as output 我想作为输出
ID SERVICE/DEV
1 PSTN
1 ADSL
1 3G
2
3 ADSL
3 2G
How to merge this? 如何合并?
I can not use classic LEFT OUTER JOIN
. 我不能使用经典的
LEFT OUTER JOIN
。
Total number in output table for one id should be the summary of T2+T3 (FOR ID=1 2+1=3)
but for ID=2
it also should exist in table output with blank second column. 输出表中一个id的总数应该是
T2+T3 (FOR ID=1 2+1=3)
的摘要T2+T3 (FOR ID=1 2+1=3)
但是对于ID=2
它也应该存在于具有空白第二列的表输出中。
You can simply combine the results of the two tables specifically T2
and T3
using union
inside a subquery the later join it with T1
using LEFT JOIN
. 你可以简单地使用子查询中的
union
将两个表的结果(特别是T2
和T3
结合起来,然后使用LEFT JOIN
将它与T1
连接起来。 Try this, 尝试这个,
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
Additionally, you can use COALESCE
if you want to customize the columns having null
values. 此外,如果要自定义具有
null
值的列,则可以使用COALESCE
。 So in the example below, since 2
has no service , it will show -none-
instead of null
因此,在下面的示例中,由于
2
没有服务 ,因此它将显示-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
Do you want union/union all? 你想要工会/工会吗?
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
The NOT IN
in the WHERE
clause may not be the most efficient way to do this. WHERE
子句中的NOT IN
可能不是最有效的方法。 But is this the result you are aiming for? 但这是你的目标吗?
You can try this. 你可以试试这个。
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(+);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.