Friday, 17 December 2021

MYSQL - For table with parent id and children, how to get all parent based on children id

 https://stackoverflow.com/questions/36523356/get-all-data-of-parent-child-relation-ship-from-same-table-in-mysql

https://www.w3schools.com/sql/func_mysql_case.asp


SELECT id,title,parent_id FROM
    (SELECT id,title,parent_id,
       CASE WHEN id = 1209 THEN @id := parent_id
            WHEN id = @id THEN @id := parent_id
            END as checkId
     FROM Test
     ORDER BY id DESC) as T
WHERE checkId IS NOT NULL


NOTE :
CASE WHEN id = 1209 then assign variable  @id with parent id
WHEN id = @id (variable @id) then variable @id = parent_id
END as checkID

This will get all parents of child starting with child id = 1209

Then filter with NOT NULL

No comments:

Post a Comment