我有两个表..在输出结果中我想合并两者的数据。所以假设我必须使用UNION语句。我在结果集中需要什么:
TABLE1------------------------------------------ COL1 COL2 COL3 1 aaa1 eee1 2 bbb1 fff1 3 ccc1 ggg1 4 ddd1 hhh1 TABLE2------------------------------------------ COL1 COL2 COL3 COL4 1 aaa2 eee2 1 2 bbb2 fff2 4 3 ccc2 ggg2 1 4 ddd2 hhh2 3 RESULT I NEED----------------------------------- COL1 COL2 COL3 1 aaa1 eee1 2 bbb1 fff1 1 aaa1 eee2 3 aaa1 ggg2
我需要这样的东西:
SELECT#1 COL1, COL2, COL3 FROM TABLE1 WHERE COL1 IN ('1','2')
UNION ALL
SELECT#2 COL1, COL2 <AS SELECT#1.COL2>, COL3 FROM TABLE2 WHERE <COL4 IN SELECT#1.COL1>
答案 0 :(得分:1)
select col1, col2, col3 from table1
WHERE COL1 IN (1,2)
union
select t2.col1,
coalesce((select col2 from table1
WHERE COL1 IN (1,2)
AND COL1 = t2.col4),
t2.col2),
t2.col3
from table2 t2 join table1 t1 on t1.col1 = t2.col1 and col4 in
(select col1 from table1 WHERE COL1 IN (1,2))
给我:
SQL>select * from table1
SQL&WHERE COL1 IN (1,2)
SQL&union
SQL&select t2.col1,
SQL& coalesce((select col2 from table1
SQL& WHERE COL1 IN (1,2)
SQL& AND COL1 = t2.col4),
SQL& t2.col2),
SQL& t2.col3
SQL&from table2 t2 join table1 t1 on t1.col1 = t2.col1 and col4 in
SQL& (select col1 from table1 WHERE COL1 IN (1,2))
SQL&;
col1 col2 col3
==== ==== ====
1 aaa1 eee1
2 bbb1 fff1
1 aaa1 eee2
3 aaa1 ggg2
4 rows found