I created a script which builds a menu with categories, sub-categories and sub-sub-categories. To get these items I use 3 separate MySQL queries. As follows:
To retrieve the main categories:
SELECT id, name FROM categories WHERE parent_id=0
To retrieve the sub-categories for each category I use:
SELECT id, name FROM categories WHERE parent_id=?
Where the ? is the id of the parent category. I then run the query again for each sub-category.
How can I optimise this script to use less sql queries ? Thank you in advance.
Try this query -
categories+sub categories:
categories+sub categories+sub sub categories:
An alternative if you only want to the parent category of a category (result row count should be equal to the number of category/subcategory rows) :
Some database servers have constructs to help these operations. However, MySQL is not one of them.
There are alternative ways to store hierarchies in a database that are more efficient. For a full story, check out this article. It will introduce you to nested sets.
http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/