简体   繁体   English

如何优化mysql查询获取类别和子类别

[英]How to optimize mysql query getting categories and subcategories

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. 为了获得这些项目,我使用3个单独的MySQL查询。 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. 是父类别的ID。 I then run the query again for each sub-category. 然后,我再次为每个子类别运行查询。

How can I optimise this script to use less sql queries ? 如何优化此脚本以使用较少的SQL查询? Thank you in advance. 先感谢您。

Try this query - 试试这个查询 -

categories+sub categories: 类别+子类别:

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

categories+sub categories+sub sub categories: 类别+子类别+子子类别:

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

Some database servers have constructs to help these operations. 某些数据库服务器具有帮助这些操作的构造。 However, MySQL is not one of them. 但是,MySQL不是其中之一。

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/ http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/

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) : 如果您只想要类别的父类别(结果行计数应该等于类别/子类别行的数量),则另一种方法:

SELECT c1.id, c1.name, c2.id, c2.name 
    FROM category c1
       LEFT JOIN category c2 ON c1.parent_id = c2.id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM