2015-07-02 158 views
0

這不是基本的父母子女等級制,而是更復雜的。不同狀態的父母子女

下面是數據的一個例子:

id parent_id status 
----------------------- 
10   10  on 
11   10  off 
12   12  off 
13   13  on 

我想是有離線數據(ID 11和12)。我的問題在於事實,即身份證11有一個「開」狀態的父母,這也應該採取。

期望的結果將是:

id parent_id status 
----------------------- 
10   10  on 
11   10  off 
12   12  off 

我寫了這麼票價爲:

SELECT t1.id, t1,parent_id 
FROM t1 
LEFT JOIN t1 t11 ON t11.id = t1.parent_id 
WHERE ((t1.status = 'off' AND t11.status='off') 
     OR (t1.status = 'off' AND t11.status='on')) 
ORDER BY t1.parent_id, t1.id 

與此查詢,我沒有與T1和T11狀態行等於「上'(這是需要的)。

的這個輸出是:

id parent_id status 
----------------------- 
(10)  (10) (on) -- missing row 
11   10  off 
12   12  off 

如何獲得所需的結果(表2)?

+0

你爲什麼不使用'WHERE t1.Status ='off''? – Siyual

+0

家長只需要1級嗎? – Amit

回答

1

你很接近,但不準確。試試這個:

SELECT t1.id, t1,parent_id 
FROM t1 
LEFT JOIN t1 t11 ON t1.id = t11.parent_id 
WHERE t1.status = 'off' OR t11.status='off' 
ORDER BY t1.parent_id, t1.id 
+0

非常感謝!這正是我想要的。 – Kaymaz