0

我有 SQLite 2 表:列:id、parent_id、值

1,0,'TOP FIRST' <---- top category "FIRST"
2,1,'11111-A'   <----subcategory of id 1 (FIRST)
3,1,'11111-B'   <----subcategory of id 1
4,0,'TOP TWO'   <---- top category "TWO"
5,4,'22222-A'   <----subcategory of id 4 (TWO)
6,4,'22222-B'   <----subcategory of id 4
7,100,'to remove'   <----- ORPHAN (There is no top category with id=100)
8,100,'to remove'   <----- ORPHAN (There is no top category with id=100)
9,4,'22222-C'   <----subcategory of id 4 (TWO)

如何从此表中删除孤儿(id:7、8)?

4

1 回答 1

1

您要删除不存在父对象的所有行。这可以通过相关子查询来完成:

DELETE FROM MyTable
WHERE NOT EXISTS (SELECT 1
                  FROM MyTable AS T2
                  WHERE T2.id = MyTable.parent_id);
于 2017-01-19T17:30:51.557 回答