删除ID与另一个表不匹配的SQL行

删除ID与另一个表不匹配的SQL行

问题描述:

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

I'm trying to delete orphan entries in a mysql table.

我有2张这样的桌子:

files:

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

blob:

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

fileidid列可用于将表连接在一起.

The fileid and id columns can be used to join the tables together.

我要删除表blob中的所有行,其中在表files.id中找不到fileid.

I want to delete all rows in table blob where fileid cannot be found in the table files.id.

因此,使用上面的示例将删除行:3& blob表中的4(s).

So using the example above that would delete rows: 3 & 4(s) in the blob table.

使用LEFT JOIN/IS NULL:

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)

使用NOT IN:

DELETE FROM BLOB
 WHERE fileid NOT IN (SELECT f.id 
                        FROM FILES f)

警告

只要有可能,就在事务中执行DELETE(假设受支持-IE:不在MyISAM上),以便在出现问题时可以使用回滚来还原更改.

Warning

Whenever possible, perform DELETEs within a transaction (assuming supported - IE: Not on MyISAM) so you can use rollback to revert changes in case of problems.