2013-04-26 53 views
1

我有以下表格:聯合並加入1個查詢?

表1:

A B C 
1 2 3 
2 4 6 
3 6 9 

TABLE2:

A B C 
4 8 12 
5 10 15 
6 12 18 

表3:

A D 
2 X 
4 Y 
6 Z 

我需要一個查詢,讓:

A B C D 
1 2 3 
2 4 6 X 
3 6 9 
4 8 12 Y 
5 10 15 
6 12 18 Z 

這可能嗎?

我能做到這一點的2個查詢,但我這樣做是爲了人希望它在1

謝謝!

回答

3

試試這個(例如在sqlfiddle):

SELECT x.a, x.b, x.c, d 
FROM (
    SELECT a, b, c FROM table1 
    UNION ALL 
    SELECT a, b, c FROM table2 
) x 
LEFT JOIN table3 ON (table3.a = x.a) 
+0

謝謝。但是我怕弗蘭克打了2分鐘! – 2013-04-26 10:12:45

+0

@DazedandConfused:其實我在Frank之前3分鐘回答;)之後我剛添加了到SQLFiddle的鏈接。 – 2013-04-26 10:35:32

+1

沒錯 - Peter的速度更快。 Upvoted。 – 2013-04-26 10:36:15

2

肯定的:

select v1.*, table3.d 
from 
    (select table1.a, table1.b, table1.c 
    from table1 
    union all 
    select table2.a, table2.b, table2.c 
    from table2 
) v1 
left join table3 on v1.a = table3.a 
+0

完美 - 非常感謝。 – 2013-04-26 10:15:08