我需要從表中刪除所有具有「for_id」參數的記錄引用此表中不存在的「id」。MySQL刪除具有參數的行不存在ID
In this example,我需要刪除name
=「tom」的行,因爲id
= 3的條目不存在。
謝謝!
我需要從表中刪除所有具有「for_id」參數的記錄引用此表中不存在的「id」。MySQL刪除具有參數的行不存在ID
In this example,我需要刪除name
=「tom」的行,因爲id
= 3的條目不存在。
謝謝!
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;
'天才!非常感謝! –
所以,你要remove
針對for_id
確實在id
換句話說not exist
這些記錄,keep
那些其for_id
確實exists
在id
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 |
不!我需要刪除所有具有「for_id」參數的記錄引用此表中不存在的「id」。 –
好吧所以你想'KEEP'所有的記錄都有「for_id」參數,這個參數是指這個表中存在的「id」?如果是,請檢查更新後的解決方案。 – batMan
如果你想刪除已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
謝謝,先生! http://sqlfiddle.com/#!9/f523d5/34 –
帶有消息'SQLSTATE [42000]的未捕獲異常'PDOException':語法錯誤或訪問衝突:1064您的SQL語法中有錯誤;檢查與您的MySQL服務器版本相對應的手冊,在正確的語法附近使用'as t1 where not exists(從類別中選擇id作爲t2,其中t2.id = t1.for_id)a'在第1行'如果我嘗試執行2 - 腳本。 –
嘗試**在反引號(')**中封裝您的字段和表名稱以使用PDO查詢 – nacho
編輯ÿ我們的帖子並將您使用的數據庫添加到標籤。 – F0XS