从其他表中删除ID不匹配的sql行

我试图删除mysql表中的孤立条目。

我有这样的2个表:

表格files

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

表格blob

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

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

我想删除表blob中的所有行,其中在表files.id

因此,使用上面的例子来删除blob表中的行:3&4(s)。

使用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上),以便在出现问题时使用回滚来还原更改。

 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...*/ ) 
 DELETE FROM blob WHERE NOT EXISTS ( SELECT * FROM files WHERE id=blob.id )