2017-10-05 22 views

回答

1
DELETE D.* FROM table_name D 
    LEFT JOIN table_name T 
    ON T.ID=D.FOR_ID 
WHERE T.ID IS NULL and D.FOR_ID<>0; 

測試上sqlfiddle.com

+0

'天才!非常感謝! –

2

所以,你要remove針對for_id確實在id
換句話說not exist這些記錄,keep那些其for_id確實existsid

SELECT * FROM table_name 
where for_id in (select id from table_name) 

或記錄使用join

SELECT t1.* FROM 
table_name t1 join table_name t2 
on t1.for_id=t2.id 

產量:

| id | for_id | lvl | name | 
|----|--------|-----|------| 
| 4 |  1 | 1 | joe | 
| 5 |  1 | 1 | mack | 
| 6 |  5 | 2 | bill | 
| 7 |  5 | 2 | rex | 
| 8 |  7 | 3 | ted | 
+0

不!我需要刪除所有具有「for_id」參數的記錄引用此表中不存在的「id」。 –

+0

好吧所以你想'KEEP'所有的記錄都有「for_id」參數,這個參數是指這個表中存在的「id」?如果是,請檢查更新後的解決方案。 – batMan

1

如果你想刪除已for_id = 0過那麼那些你可以使用:

DELETE 
FROM table_name as t1 
where not exists (select id 
     from table_name as t2 
     where t2.id=t1.for_id) 

,如果你不想刪除已for_id = 0您可以將那些用途:

delete 
FROM table_name as t1 
where not exists (select id 
     from table_name as t2 
     where t2.id=t1.for_id) and t1.for_id<>0 
+0

謝謝,先生! http://sqlfiddle.com/#!9/f523d5/34 –

+0

帶有消息'SQLSTATE [42000]的未捕獲異常'PDOException':語法錯誤或訪問衝突:1064您的SQL語法中有錯誤;檢查與您的MySQL服務器版本相對應的手冊,在正確的語法附近使用'as t1 where not exists(從類別中選擇id作爲t2,其中t2.id = t1.for_id)a'在第1行'如果我嘗試執行2 - 腳本。 –

+0

嘗試**在反引號(')**中封裝您的字段和表名稱以使用PDO查詢 – nacho