MySQL chained select -


i have table family

+----------------------------+ | id | name   | age | parent | |----------------------------| | 1  | father | 60  | null   | |----------------------------| | .. | ...... | ..  | .....  | | n  | luke   | 20  | n      | +----------------------------+ 

the column parent reference family - id. starting of father, how can select last descendant using single select query?

the long way n = select * family parent = 1 , o = select * family parent = n, etc.

do recursive query :

select @pv:=id family join (select @pv:=1)tmp parent=@pv 

to last descendant use max aggregate function

select max(@pv:=id) family join (select @pv:=1)tmp parent=@pv 

update : other way around. ancestor please test query

select min(case when parent null         id         else @pv:=parent end) ancestor family join (select @pv:=3)tmp (case when parent null or id=@pv        1 else 0 end) = 1 

Comments

Popular posts from this blog

How to check data type in C++? -

javascript - Is getTimezoneOffset() stable during daylight saving transition? -

sql server - SQL Query returns one result, does not return 0 or NULL result -