2009-09-23 59 views
0

我不記得如何加入一個表與自身加入..我的表是:留在同一個表

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

,我需要檢索值山坳其中PROC爲$ proc和那種既「 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| 

相反,我查詢我不得到anythong如果b或一行丟失。

我正在與MySQL ...如何做到這一點?

編輯: 我可以使用UNION子句,但是這不會讓我有一個NULL值,當一個行缺少(KIND =一個或KIND = B)

回答

1

你必須做一個完整的加盟情況下PROC存在「一」,但不是「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' 

編輯:1日給MS SQL Server查詢(FULL JOIN),但顯然它不是MySQL支持的,所以我把它改爲2 LEFT的UNION JOIN

+0

意識形態上是我需要的,但我得到錯誤附近的完全加入.. mysql是否支持完全加入? – Strae 2009-09-23 09:20:15

+0

我將查詢修改爲2 LEFT JOIN的UNION。 – manji 2009-09-23 09:28:30

+0

我們贏了!有用。但它的複雜性看起來像是我的數據庫表的錯誤設計的警報,我會再次檢查我的結構,如果有一個更簡單和更快捷的方式..謝謝你! – Strae 2009-09-23 09:33:35

0

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

+0

不工作.... – Strae 2009-09-23 08:40:57

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' 
+0

這種解決方案也是如此,謝謝! – Strae 2009-09-23 09:36:47

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