2016-06-21 42 views
3

我有表和記錄,如下面刪除父ID記錄,如果列包含`id`在父列的MySQL

模板

id  name   parent 

1  template1 0 
2  template2 0 
3  template3 1 

,我想這樣的輸出,

id  name   parent 

2  template2 0 
3  template3 1 

正如你所看到的#3有父母#1,所以需要使用單個查詢從查詢​​中取消選擇。

在此先感謝。

回答

2

您可以使用NOT EXISTS()

SELECT * FROM templates t 
WHERE NOT EXISTS(SELECT 1 FROM templates s 
       WHERE s.parent = t.id) 

還是一個LEFT JOIN

SELECT t.* FROM templates t 
LEFT JOIN templates s 
ON(t.id = s.parent) 
WHERE s.id is null 

或者NOT IN()

SELECT * FROM templates t 
WHERE t.id NOT IN(SELECT parent FROM templates) 
+0

嗨,你回答沒有爲我工作,但我想從你一些建議。如果我使用這樣的查詢'WHERE t.id NOT IN(SELECT父模板)和狀態='1'它不適合我,似乎AND子句不與'NOT IN'一起工作? – hemsbhardiya

+0

不,將「NOT IN」與任何東西結合都沒有問題。也許是與你的數據的東西..張貼一個例子,它不起作用,我會告訴你爲什麼。 @HimanshuBhardiya – sagi

2

試試這個;)

select t1.* 
from templates t1 
left join templates t2 on t1.id = t2.parent 
where t2.id is null 

DEMO HERE

2

檢查:

SELECT * FROM `templates` where id NOT IN (SELECT parent FROM `templates` where parent!=0 GROUP BY parent);