There is a navigation table
navigations id parent_id name The table is linked with navigations.parent_id on navigations.id
How to write a query that will recursively search for a name in it or in its parents?
Suppose my table consists of the following columns with values:
id parent_id name 1 0 aaa 2 1 bbb 3 2 ccc the value of the name column is unique, not repeated.
It is necessary to find name = 'aaa' where id = 3, if it does not find it, continue to search in its parent (id = 2) , and so on until it gets to id = 1 where name= 'aaa' because id=3 is in its parent chain
Need a query at the level of sql.
here is my code. But it does not work as I need:
SELECT `pn`.`id` AS `parent_id` FROM `navigations` `pn` INNER JOIN `navigations` `ch_n` ON `ch_n`.`parent_id` = `pn`.`id` WHERE `ch_n`.`name` = 'aaa' With the help of this query at the PHP level, I can implement it, but I need it at the query level. To get the ready result.
Is it possible ?
Thank you for your help