2010-07-30 26 views
2

的MySQL數據庫表示我有兩個表表示父/子節點,它們的類型,以及它們之間的關係:查詢樹

表1

| nodeID | node | name | type | 
| 1  | A | test | Type A | 
| 2  | B | abcd | Type B | 
| 3  | C | defg | Type C | 

表2

| parentNodeID | childNodeID | 
|  1   |  2  | 
|  1   |  3  | 

我想寫一個查詢,我發現類型B的孩子節點沒有類型C的父母。

我試過

select node from table1 t1 left join table2 t2 on t1.nodeID=t2.childNodeID 
    where Type="Type B" 
    and t2.parentNodeID not in (select nodeID from t1 where type="Type C) 

這不像預期的那樣工作。我是否正確地做這件事?有更容易的方法嗎?

+0

關於您的查詢的具體內容不按預期工作(我假設它不是明顯的打字錯誤)。你能舉一個例子,你的查詢不能給出正確的結果嗎? – 2010-07-30 13:53:51

回答

1

你可以試試這個:

SELECT node 
FROM Table1 
WHERE type = 'Type B' 
AND nodeID NOT IN (
    SELECT T2.childNodeID 
    FROM table1 T1 
    JOIN table2 T2 
    ON T2.parentNodeId = T1.nodeId 
    WHERE T1.type = 'Type C' 
) 

這意味着這樣的事情:查找不屬於(即C型的父節點的子節點)的一個B類型的所有節點。