Mysql
 sql >> Database >  >> RDS >> Mysql

Come ottimizzare le query mysql ottenendo categorie e sottocategorie

Prova questa query -

categorie+sottocategorie:

SELECT c1.id, c1.name, c2.id, c2.name FROM categories c1
  LEFT JOIN categories c2
    ON c2.parent_id = c1.id
WHERE c1.parent_id = 0

categorie+sottocategorie+sottosottocategorie:

SELECT c1.id, c1.name, c2.id, c2.name, c3.id, c3.name FROM categories c1
  LEFT JOIN categories c2
    ON c2.parent_id = c1.id
  LEFT JOIN categories c3
    ON c3.parent_id = c2.id
WHERE c1.parent_id = 0