删除其中ID与另一个表不匹配的sql行

时间:2010-08-01 23:18:49

标签: sql mysql

我正在尝试删除mysql表中的孤立条目。

我有2张这样的表:

files

| id | ....
------------
| 1  | ....
| 2  | ....
| 7  | ....
| 9  | ....

blob

| fileid | ....
------------
| 1  | ....
| 2  | ....
| 3  | ....
| 4  | ....
| 4  | ....
| 4  | ....
| 9  | ....

可以使用fileidid列将表连接在一起。

我想删除表格blob中无法在表格fileid中找到files.id的所有行。

所以使用上面会删除行的示例:3& blob表中的4(s)。

4 个答案:

答案 0 :(得分:279)

使用LEFT JOIN / IS NULL:

DELETE b FROM BLOB b 
  LEFT JOIN FILES f ON f.id = b.fileid 
      WHERE f.id IS NULL

使用NOT EXISTS:

DELETE FROM BLOB 
 WHERE NOT EXISTS(SELECT NULL
                    FROM FILES f
                   WHERE f.id = fileid)

使用NOT IN:

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);