删除id不与另一个表匹配的sql行

时间:2021-07-26 21:36:28

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

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

I have 2 tables like this:

我有两张这样的桌子:

Table files:

表文件:

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

table blob:

表团:

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

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

fileid和id列可用于将表连接在一起。

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

我想删除表blob中的所有行,其中无法在表文件.id中找到文件id。

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

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

3 个解决方案

#1


217  

Using LEFT JOIN/IS NULL:

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

Using NOT EXISTS:

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

Using NOT IN:

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

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.

在可能的情况下,在事务中执行删除操作(假设支持——IE:不在MyISAM上),这样您就可以使用rollback来恢复发生问题时的更改。

#2


20  

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...*/
      )

#3


9  

DELETE FROM blob
WHERE NOT EXISTS (
    SELECT *
    FROM files
    WHERE id=blob.id
)

#1


217  

Using LEFT JOIN/IS NULL:

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

Using NOT EXISTS:

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

Using NOT IN:

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

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.

在可能的情况下,在事务中执行删除操作(假设支持——IE:不在MyISAM上),这样您就可以使用rollback来恢复发生问题时的更改。

#2


20  

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...*/
      )

#3


9  

DELETE FROM blob
WHERE NOT EXISTS (
    SELECT *
    FROM files
    WHERE id=blob.id
)