在dtree中删除孤儿(SQLite 2)

时间:2017-01-19 16:44:17

标签: sqlite2

我有SQLite 2表: 列: id,parent_id,value

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)?

1 个答案:

答案 0 :(得分:0)

您要删除所有不存在父级的行。这可以使用correlated subquery

来完成
DELETE FROM MyTable
WHERE NOT EXISTS (SELECT 1
                  FROM MyTable AS T2
                  WHERE T2.id = MyTable.parent_id);