Search code examples
mysqlsqlparent-childparent

MYSQL parent relations


I have this table structured like this

CATEGORIE

id name categorie_id

Some categories are nested so categorie 1 is going to be in categorie 2 and categorie 3.

I would like to display all the names of categories and also their attributed parents in a query.

How can I do that ?


Solution

  • Just join with self.

    select t1.name, t2.name as parent_name 
    from categories t1 
    left join categories t2 on t1.parent_id = t2.id
    

    Change categorie_id to parent_id for more readable.