Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select all rows that have no children

Tags:

mysql

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 can avoid.

like image 935
kylex Avatar asked Feb 16 '11 17:02

kylex


1 Answers

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
like image 156
Joe Stefanelli Avatar answered Oct 27 '22 18:10

Joe Stefanelli