选择所有没有子项的行

kyl*_*lex 12 mysql

我真的在这一次失败了.

我有下表:

id    parentID     name
1     0            Frank
2     1            Sally
3     1            John
4     3            Beth

我想要一个只选择那些没有子项的项的语句,所以在前面的例子中:

Sally
Beth
Run Code Online (Sandbox Code Playgroud)

结果会是.似乎无法在不创建递归函数的情况下找出执行此操作的查询,如果可以避免,我不想这样做.

Joe*_*lli 15

select yt.name
    from YourTable yt
    where not exists (select null from YourTable where parentID = yt.id)
Run Code Online (Sandbox Code Playgroud)

虽然效率较低(参见:Left outer join vs NOT EXISTS),但您也可以使用左连接执行此操作:

select yt1.name
    from YourTable yt1
        left join YourTable yt2
            on yt1.id = yt2.parentID
    where yt2.id is null
Run Code Online (Sandbox Code Playgroud)


rye*_*3ad 5

select t.name
from that_table t
where t.id not in (select parentID from that_table);
Run Code Online (Sandbox Code Playgroud)