左连接在同一个表上

时间:2009-09-23 08:22:11

标签: mysql left-join

我不记得如何将表连接到自己..我的表是:

| id | proc | value | kind |
| 1  | 1    | foo   | a    |
| 2  | 1    | bar   | b    |
| 3  | 2    | some  | a    |

我需要检索值为col的地方,其中proc是$ proc,kind是'a'和'b'..好吧,我需要做那个(寻找proc = 1):

| v_a | v_b |
| foo | bar |

所以我写了这个查询:

SELECT
    a.value AS v_a,
    b.value AS v_b
FROM
    (SELECT value FROM table WHERE proc = '1' AND kind = 'a') AS a,
    (SELECT value FROM table WHERE proc = '1' AND kind = 'b') AS b

并且有效,但只有在表中我有两行for kind = a和kind = b。

但我需要,如果错过一行,我将有一个空值:如果我寻找proc = 2我必须得到:

| v_a | v_b |
| foo | NULL|

相反,根据我的查询,如果b或行丢失,我就不会得到任何东西。

我正在使用mysql ......怎么做?

修改 我可以使用UNION子句,但是当一行丢失时,这不允许我有一个NULL值(kind = a或kind = b)

4 个答案:

答案 0 :(得分:1)

我错过了检索NULL的必要性。这很复杂,但似乎有效:

SELECT
    a.value AS a_val,
    (SELECT value FROM t b2 WHERE b2.proc = a.proc AND b2.id != a.id) AS b_val
FROM `t` a
WHERE a.kind = 'a'

UNION DISTINCT

SELECT
    (SELECT value FROM t a2 WHERE a2.proc = b.proc AND a2.id != b.id) AS a_val,
    b.value AS b_val
FROM `t` b
WHERE b.kind = 'b'

答案 1 :(得分:1)

你必须做一个完整的连接,以便存在'a'而不是'b'的情况,反之亦然:

SELECT
    a.value v_a, 
    b.value v_b
FROM (SELECT proc, value FROM tab WHERE kind = 'a') a LEFT JOIN 
(SELECT proc, value FROM tab WHERE kind = 'b') b
  ON a.proc = b.proc
WHERE a.proc = '1'
UNION
SELECT
    a.value v_a, 
    b.value v_b
FROM (SELECT proc, value FROM tab WHERE kind = 'b') b LEFT JOIN 
(SELECT proc, value FROM tab WHERE kind = 'a') a
  ON a.proc = b.proc
WHERE b.proc = '1'
编辑:第一个给了MS SQL Server查询(FULL JOIN),但显然它不受MYSQL的支持,所以我把它改成了2 LEFT JOIN的UNION

答案 2 :(得分:0)

select * from t1 full outer join t2 on some_id = some_other_id

答案 3 :(得分:0)

SELECT
    a.value AS v_a,
    b.value AS v_b
FROM
    (SELECT proc, value FROM table WHERE proc = '1' AND kind = 'a') AS a
LEFT OUTER JOIN
    (SELECT proc, value FROM table WHERE proc = '1' AND kind = 'b') AS b
ON a.proc=b.proc