MySQL 删除具有引用不存在 ID 的参数的行
MySQL delete rows that have parameter which refers to the not exist ID
我需要从 table 中删除所有具有 "for_id" 参数的记录,指的是 "id" 不存在于此 table 中。
In this example,我需要删除带有 name
=" tom " 的行,因为带有 id
= 3 的条目不存在。
谢谢!
因此您想要 remove
for_id
在 id
中 not exist
的那些记录
换句话说,keep
for_id
在 id
中 exists
的那些记录
SELECT * FROM table_name
where for_id in (select id from table_name)
或使用join
:
SELECT t1.* FROM
table_name t1 join table_name t2
on t1.for_id=t2.id
输出:
| id | for_id | lvl | name |
|----|--------|-----|------|
| 4 | 1 | 1 | joe |
| 5 | 1 | 1 | mack |
| 6 | 5 | 2 | bill |
| 7 | 5 | 2 | rex |
| 8 | 7 | 3 | ted |
如果你也想删除那些 for_id=0 那么你可以使用:
DELETE
FROM table_name as t1
where not exists (select id
from table_name as t2
where t2.id=t1.for_id)
如果您不想删除 for_id=0 的那些,您可以使用:
delete
FROM table_name as t1
where not exists (select id
from table_name as t2
where t2.id=t1.for_id) and t1.for_id<>0
DELETE D.* FROM table_name D
LEFT JOIN table_name T
ON T.ID=D.FOR_ID
WHERE T.ID IS NULL and D.FOR_ID<>0;
我需要从 table 中删除所有具有 "for_id" 参数的记录,指的是 "id" 不存在于此 table 中。
In this example,我需要删除带有 name
=" tom " 的行,因为带有 id
= 3 的条目不存在。
谢谢!
因此您想要 remove
for_id
在 id
中 not exist
的那些记录
换句话说,keep
for_id
在 id
exists
的那些记录
SELECT * FROM table_name
where for_id in (select id from table_name)
或使用join
:
SELECT t1.* FROM
table_name t1 join table_name t2
on t1.for_id=t2.id
输出:
| id | for_id | lvl | name |
|----|--------|-----|------|
| 4 | 1 | 1 | joe |
| 5 | 1 | 1 | mack |
| 6 | 5 | 2 | bill |
| 7 | 5 | 2 | rex |
| 8 | 7 | 3 | ted |
如果你也想删除那些 for_id=0 那么你可以使用:
DELETE
FROM table_name as t1
where not exists (select id
from table_name as t2
where t2.id=t1.for_id)
如果您不想删除 for_id=0 的那些,您可以使用:
delete
FROM table_name as t1
where not exists (select id
from table_name as t2
where t2.id=t1.for_id) and t1.for_id<>0
DELETE D.* FROM table_name D
LEFT JOIN table_name T
ON T.ID=D.FOR_ID
WHERE T.ID IS NULL and D.FOR_ID<>0;