2017-08-08 59 views
1

我有一個表象下面這樣:SQL查詢來找到內,葉和根節點

ID P_ID 
1  2 
3  2 
6  8 
9  8 
2  5 
8  5 
5  null 

我已經使用了查詢

SELECT ID, 
    CASE 
     WHEN P_ID IS NULL THEN 'Root' 
     WHEN NOT EXISTS (SELECT ID FROM MINOA.TREE WHERE P_ID=T0.ID) THEN 'Leaf' 
     ELSE 'Inner' 
    END T 
FROM MINOA.TREE T0 
ORDER BY ID; 

我得到的輸出是:

ID  P_ID 
1  leaf 
2  inner 
3  leaf 
5  inner 
6  leaf 
8  inner 
9  leaf 

但是對於ID 5,它應該已經返回Root

+0

你爲什麼叫喊? –

+0

正因爲如此,你再次調用表的時候,'SELECT ID FROM MINOA.TREE WHERE P_ID = T0.ID'。在這裏顯示更多細節。你怎麼會出現'葉子'以及'內部'的結果。 –

回答

0

我已經創建這樣的表:

+-------+---------+------+-----+---------+-------+ 
| Field | Type | Null | Key | Default | Extra | 
+-------+---------+------+-----+---------+-------+ 
| id | int(11) | YES |  | NULL |  | 
| p_id | int(11) | YES |  | NULL |  | 
+-------+---------+------+-----+---------+-------+ 

有了自己的價值觀:

+------+------+ 
| id | p_id | 
+------+------+ 
| 1 | 2 | 
| 3 | 2 | 
| 6 | 8 | 
| 9 | 8 | 
| 2 | 5 | 
| 8 | 5 | 
| 5 | NULL | 
+------+------+ 

執行這個查詢:

SELECT id, CASE WHEN p_id IS NULL THEN 'Root' WHEN NOT EXISTS (SELECT id FROM tree WHERE p_id = t0.id) THEN 'Leaf' ELSE 'Inner' END as PROPERTY from tree t0 order by id; 

返回:

+------+----------+ 
| id | PROPERTY | 
+------+----------+ 
| 1 | Leaf  | 
| 2 | Inner | 
| 3 | Leaf  | 
| 5 | Root  | 
| 6 | Leaf  | 
| 8 | Inner | 
| 9 | Leaf  | 
+------+----------+