删除ID与另一个表不匹配的SQL行 [英] Delete sql rows where IDs do not have a match from another table

查看:232
本文介绍了删除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.

这篇关于删除ID与另一个表不匹配的SQL行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆