对查询的唯一改进是使用union all而不是union. 仅union在您明确要删除重复项时使用,因为它总是尝试:
SELECT A, B, Col1, Col2, null as Col3, null as Col4 FROM Table1
UNION ALL
SELECT A, B, null as Col1, null as Col2, Col3, Col4 FROM Table2
UNION ALL
SELECT A, B, Col1, Col2, null as Col3, Col4 FROM Table3;
编辑:
您可以进一步简化为:
SELECT A, B, Col1, Col2, null as Col3, null as Col4 FROM Table1
UNION ALL
SELECT A, B, null, null, Col3, Col4 FROM Table2
UNION ALL
SELECT A, B, Col1, Col2, null, Col4 FROM Table3;
列名仅用于select. union all之后,按位置标识列。
编辑二:
有一个技巧可以用来在union all. 我不是特别喜欢它,但您不必列出所有子查询的列。但是,select更复杂,它还有另一个子查询,您仍然需要子查询:
select coalesce(t1.A, t2.A, t3.A) as A,
coalesce(t1.B, t2.B, t3.B) as B,
coalesce(t1.Col1, t2.Col1, t3.Col1) as col1,
coalesce(t1.Col2, t2.Col2, t3.Col2) as col2,
coalesce(t1.Col3, t2.Col3, t3.Col3) as col3
from (select 'Table1' as tablename union all
select 'Table2' union all
select 'Table3'
) driver left outer join
(select t.*, 'Table1' as tablename
from Table1
) t1
on t1.tablename = driver.tablename left outer join
(select t.*, 'Table2' as tablename
from Table2
) t2
on t2.tablename = driver.tablename left outer join
(select t.*, 'Table3' as tablename
from Table3
) t3
on t3.tablename = driver.tablename;