查询自关联类别表
我正在尝试优化下表的 php 代码,
Create table categories (
cat_id Int UNSIGNED NOT NULL AUTO_INCREMENT,
parent_id Int UNSIGNED,
cat_name Varchar(50) NOT NULL,
Primary Key (cat_id)) ENGINE = InnoDB;
为了获取所有类别和子类别,我使用一个查询仅查询父类别,然后发出单独的查询来获取子类别。
这是我列出所有主要类别的代码
$result = mysql_query("SELECT cat_id, cat_name FROM categories WHERE parent_id IS NULL");
要列出我使用以下查询的每个类别的各个子类别,
$sub_result = mysql_query ("SELECT cat_id, cat_name FROM categories WHERE parent_id=$cat_id");
我有 30 个类别,因此上述问题在每个页面上有 30 个查询,我试图最大限度地减少查询数量。有什么提示吗?
谢谢
I am trying to optimize my php code for the following table
Create table categories (
cat_id Int UNSIGNED NOT NULL AUTO_INCREMENT,
parent_id Int UNSIGNED,
cat_name Varchar(50) NOT NULL,
Primary Key (cat_id)) ENGINE = InnoDB;
To get all categories and subcategories i use one query for querying only parent categories and then issue an individual query to get the sub categories.
here is my code for listing the all main categories
$result = mysql_query("SELECT cat_id, cat_name FROM categories WHERE parent_id IS NULL");
To list individual subcategories of each category i use following query
$sub_result = mysql_query ("SELECT cat_id, cat_name FROM categories WHERE parent_id=$cat_id");
I have 30 categories so the above issues 30 queries on each page, I am trying to minimize the number of queries. Any hint?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
关于管理分层数据的文章可能会给您一些启发。不要因为它位于 MySQL 站点上而感到沮丧,主要思想是相同的。
The article on managing hierarchical data might give you some inspiration. Don't be discouraged by the fact that it's on MySQL site, the main ideas are the same.
这在 MySQL 中很困难,因为缺乏对递归查询的支持。
有多种替代方法可以构建表,以便您可以在单个查询中查询层次结构的所有后代。但它们涉及改变存储数据的方式。
请参阅我的演示文稿使用 SQL 和 PHP 实现分层数据的模型,了解演示多个模型的示例解决方案。
This is tough in MySQL because of lack of support for recursive queries.
There are several alternative ways to structure your table so you can query all descendants of a hierarchy in a single query. But they involve changing the way you store data.
See my presentation Models for Hierarchical Data with SQL and PHP for examples demonstrating several solutions.