S.M_Emamian S.M_Emamian - 1 month ago 7
SQL Question

How to get last category of a self-join table

I have a table like this (this table is my categories of products) :

id title parent_id
1 A 0
2 A1 1
3 A2 1
4 B 0
5 A11 2
6 B1 4


now,How can I get last of sub-categories ?
for example :

B1
A11
A2

Answer

You seem to want the rows that are not the parent of another row:

select pc.*
from productcategories pc
where not exists (select 1
                  from productcategories pc2
                  where pc2.parent_id = pc.id
                 );
Comments