开发者

Select all rows that have no children

I'm really having a brain-fail on this one.

I have the following table:

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

I'd like a statement that selects only those items that have no children, so in the previous example:

Sally
Beth

Would be the result. Can't seem to figure out a query to do this without creating a recursive function, which I don't want do to if I ca开发者_开发知识库n avoid.


select yt.name
    from YourTable yt
    where not exists (select null from YourTable where parentID = yt.id)

Although less efficient (see: Left outer join vs NOT EXISTS), you could also do this with a left join:

select yt1.name
    from YourTable yt1
        left join YourTable yt2
            on yt1.id = yt2.parentID
    where yt2.id is null


select t.name
from that_table t
where t.id not in (select parentID from that_table);


select person.ID, person.name
FROM table AS person
LEFT OUTER JOIN table AS child ON person.ID = child.parentID
WHERE child.parentID IS NULL

or in less efficient form

select person.ID, person.name, count(child.id) AS number_of_children
FROM table AS person
LEFT JOIN table AS child on person.ID = child.parentID
GROUP BY person.id
HAVING number_of_children = 0


SELECT p.id, 
    (SELECT count(c.id) FROM yourtable AS c WHERE c.parent_id=p.id) AS childs
    FROM yourtable AS p 
        WHERE 1
HAVING childs = 0
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜