对您的查询的唯一改进是使用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;
列名仅用于对于union all
中的第一个select
。之后,这些列按位置标识。
编辑II:
有一个小窍门,你可以用它来获得“逻辑”上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;
如果table1有3行,table2有3行,那么bigtable会有多少行? –
它将有6行 –