0

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

| 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

并且有效,但前提是在表中我有 kind=a 和 kind=b 的两行。

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

| v_a | v_b |
| foo | NULL|

相反,通过我的查询,如果缺少 b 或 a 行,我不会得到任何信息。

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

编辑: 我可以使用 UNION 子句,但是当缺少一行(种类=a 或种类=b)时,这不允许我有一个 NULL 值

4

4 回答 4

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'
于 2009-09-23T08:49:16.557 回答
1

如果 proc 存在 '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

于 2009-09-23T08:50:40.347 回答
0

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

于 2009-09-23T08:35:33.153 回答
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
于 2009-09-23T10:46:08.287 回答