我正在尝试删除mysql表中的孤立条目。
我有2张这样的表:
表files
:
| id | ....
------------
| 1 | ....
| 2 | ....
| 7 | ....
| 9 | ....
表blob
:
| fileid | ....
------------
| 1 | ....
| 2 | ....
| 3 | ....
| 4 | ....
| 4 | ....
| 4 | ....
| 9 | ....
可以使用fileid
和id
列将表连接在一起。
我想删除表格blob
中无法在表格fileid
中找到files.id
的所有行。
所以使用上面会删除行的示例:3& blob
表中的4(s)。
答案 0 :(得分:279)
DELETE b FROM BLOB b
LEFT JOIN FILES f ON f.id = b.fileid
WHERE f.id IS NULL
DELETE FROM BLOB
WHERE NOT EXISTS(SELECT NULL
FROM FILES f
WHERE f.id = fileid)
DELETE FROM BLOB
WHERE fileid NOT IN (SELECT f.id
FROM FILES f)
尽可能在事务中执行DELETE(假设支持 - IE:不在MyISAM上),因此您可以使用回滚在出现问题时还原更改。
答案 1 :(得分:26)
DELETE FROM blob
WHERE fileid NOT IN
(SELECT id
FROM files
WHERE id is NOT NULL/*This line is unlikely to be needed
but using NOT IN...*/
)
答案 2 :(得分:13)
DELETE FROM blob
WHERE NOT EXISTS (
SELECT *
FROM files
WHERE id=blob.id
)
答案 3 :(得分:0)
delete from table1 t1
WHERE not exists (select id from table2 where related_field_in_t2=t1.id)
AND not exists (select id from table3 where related_field_in_t3=t1.id)
AND not exists (select id from table4 where related_field_t4=t1.id)
AND not exists (select id from table5 where related_field_t5=t1.id);