从 table 中查找所有最后 children

Find all last children from a table

idTask  idParent  Description
1                 Root  
2          1      Parent-1
3          1      Parent-2
4          1      Parent-3
5          1      Parent-4
6          4      Child31   
7          4      Child32   
8          5      Child41   
9          8      Child411
10         8      Child412

我需要一个查询来检索这样的记录,

输出

2          1      Parent-1
3          1      Parent-2
6          4      Child31   
7          4      Child32   
9          8      Child411
10         8      Child412
select * from task t1 where not exists (select 1 from task where idParent = t1.idTask)

如果您指的是树中的叶子,您可以通过自连接 table 并查找 NULL 记录来查找没有子项的行:

SELECT parent.Id 
FROM task parent LEFT OUTER JOIN task child on child.idParent= parent.IdTask
WHERE child.IdTask IS NULL