假设我们有一个 mysql 表
Id RelatedId
1 0
2 0
3 1
4 2
5 1
6 2
如何在单个 MySQL 查询中删除 RelatedId=0 的所有记录,然后删除 Id=RelatedId 上的子项?
假设我们有一个 mysql 表
Id RelatedId
1 0
2 0
3 1
4 2
5 1
6 2
如何在单个 MySQL 查询中删除 RelatedId=0 的所有记录,然后删除 Id=RelatedId 上的子项?
ClaireG 的答案的替代方法是强制与设置为 ON DELETE CASCADE 的外键的关系。
您必须检查两次:
DELETE FROM [yourTableName]
WHERE RelatedId = 0
OR (RelatedId in
(select id from [yourTableName] where RelatedId = 0))
查找相关ID为空的所有记录,并查找与0相关的所有其他ID(在您的情况下[1,2]
)
似乎有效...
DELETE
FROM
delete_table
WHERE
delete_table.RelatedId IN (
select Id from(
SELECT
s1.Id
FROM
delete_table s1
WHERE
s1.RelatedId = 0
) as x
)
OR delete_table.RelatedId = 0;
DELETE TABLENAME
FROM TABLENAME T1
WHERE TABLENAME.ID = T1.RELTED_ID AND T1.RELTED_ID = 0;