MySQL让父母拥有相同的id和相关的孩子

时间:2013-08-13 12:24:58

标签: mysql

假设我们有一个mysql表

Id    RelatedId
1     0
2     0
3     1
4     2
5     1
6     2

如何在单个MySQL查询中删除所有记录为RelatedId = 0,然后删除Id = RelatedId上的子记录?

4 个答案:

答案 0 :(得分:1)

Claire的答案的替代方法是强制与设置为ON DELETE CASCADE的外键的关系。

答案 1 :(得分:0)

你必须检查两次:

DELETE FROM [yourTableName] 
WHERE RelatedId = 0
   OR (RelatedId in 
         (select id from [yourTableName] where RelatedId = 0))

查找relatedID为null的所有记录,并查找与0相关的所有其他ID(在您的情况下为[1,2]

答案 2 :(得分:0)

似乎有效......

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;

答案 3 :(得分:0)

DELETE TABLENAME 
FROM TABLENAME T1
WHERE TABLENAME.ID = T1.RELTED_ID AND T1.RELTED_ID = 0;