MySQL:左联盟与正确联接

时间:2009-09-17 19:13:26

标签: sql mysql

假设我们有以下表格t1和t2:

t1:
id | column_1
-------------
 1 |   1
 2 |   2

t2:
id | column_2
-------------
 2 |   2
 3 |   3

我们希望找到以下结果:

id | column_1 | column_2
------------------------
 1 |  1       | 
 2 |  2       | 2
 3 |          | 3

这基本上是右连接与左连接的并集。以下代码有效,但感觉很笨拙:

(
    SELECT t1.id, t1.column_1, t2.column_2 
    FROM t1 
    LEFT JOIN t2 ON t1.id = t2.id
)
UNION
(
    SELECT t2.id, t1.column_1, t2.column_2 
    FROM t1 
    RIGHT JOIN t2 ON t1.id = t2.id
)

有没有更好的方法来实现这一目标?

3 个答案:

答案 0 :(得分:7)

select a.id, t1.column_1, t2.column_2
from (
    select id from t1
    union 
    select id from t2
) a
left outer join t1 on a.id = t1.id
left outer join t2 on a.id = t2.id

答案 1 :(得分:1)

试试这个:

SELECT t1.id, t1.column_1, t2.column_2 
FROM t1 
FULL OUTER JOIN t2 ON (t1.id = t2.id)

编辑:不起作用,MySQL不知道FULL OUTER JOIN。 看看这里: http://www.xaprb.com/blog/2006/05/26/how-to-write-full-outer-join-in-mysql/

答案 2 :(得分:0)

我自己没试过,但这可能有效:

SELECT t1.id, t1.column_1, t2.column_2, t2a.column_2
FROM t1     
LEFT JOIN t2 ON t1.id = t2.id
RIGHT JOIN t2 AS t2a ON t1.id = t2a.id