Delete sql rows where IDs do not have a match from another table(从另一个表中删除 ID 不匹配的 sql 行)
问题描述
我正在尝试删除 mysql 表中的孤立条目.
I'm trying to delete orphan entries in a mysql table.
我有 2 张这样的桌子:
I have 2 tables like this:
表文件:
| id | ....
------------
| 1 | ....
| 2 | ....
| 7 | ....
| 9 | ....
表blob:
| fileid | ....
------------
| 1 | ....
| 2 | ....
| 3 | ....
| 4 | ....
| 4 | ....
| 4 | ....
| 9 | ....
fileid 和 id 列可用于将表连接在一起.
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
使用 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 上),以便在出现问题时可以使用回滚来恢复更改.
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 行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从另一个表中删除 ID 不匹配的 sql 行
基础教程推荐
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- oracle区分大小写的原因? 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- 在多列上分布任意行 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
