對您的查詢的唯一改進是使用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行 –