MYSQL:创建一个查询以显示条目的父/层次结构(Breadcrumbs)

时间:2014-01-17 23:14:42

标签: php mysql sql treeview

我有一张这样的表:

--------------------Categories-------------------
| Category      | Label         | Parent        |
*************************************************
| /             | Home          | NULL          |
-------------------------------------------------
| leasing       | Leasing       | /             |
-------------------------------------------------
| leasing-steps | Leasing Steps | leasing       |
-------------------------------------------------
| new-tenant    | New Tenants   | leasing-steps |
-------------------------------------------------
| properties    | Properties    | leasing       |
-------------------------------------------------
| about         | About Us      | /             |
-------------------------------------------------

我从PHP接收变量(类别),假设值为'leasing-steps'

我需要提出一个SQL查询,它将能够采用任何类别,并以正确的顺序给我它的层次结构。对于此示例('leasing-steps'),它必须输出:

 ---Categories---
| Category      |
*****************
| /             | 
-----------------
| leasing       |
-----------------
| leasing-steps |
-----------------

我试过了:

SELECT `Cat1`.`Category`
FROM Categories AS `Cat1`
LEFT JOIN Categories AS `Cat2` ON `Cat1`.`Parent`
WHERE `Cat1`.`Category` = 'leasing-steps'

但它只给我一个条目而不是所需的结果。

请记住,我正与未知数量的父母一起工作。它可能是1级或99999

2 个答案:

答案 0 :(得分:2)

问题是你的数据库模型,如果深度总是三个或更少,你可以修复一个任务,但这不是一个好的解决方案。也许有想法阅读以下有关MySQL中分层数据的文章:http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/

答案 1 :(得分:1)

您可以编写一个存储过程,创建一个临时表并循环遍历每个节点并插入类别,直到父节点为NULL,然后从该临时表ORDER按相反顺序进行SELECT,以便更高的节点首先显示然后删除你完成这样的临时表sqlFiddle

CREATE PROCEDURE get_hierchy(IN in_category varchar(50))
BEGIN
 CREATE TEMPORARY TABLE _categories(id int auto_increment primary key,category varchar(50));
 SET @category = NULL;
 SET @parent = in_category;
 WHILE(@parent IS NOT NULL) DO
    SET @nextparent = @parent;
    SET @parent = NULL;
    SELECT category,parent INTO @category,@parent FROM categories WHERE category = @nextparent;
    INSERT INTO _categories(category) values (@category);
 END WHILE;
 SELECT category FROM _categories ORDER BY id DESC;
 DROP TABLE _categories;
END//  

或者如果auto_incremented id表中有categories,并且如果您知道层次结构中较高层的节点将始终在较低节点之前创建,则可以使用此查询({{ 3}})

SELECT category
FROM
  (SELECT @parent:=parent as newparent,
          category,parent,
          id
   FROM categories
   JOIN(SELECT @parent:='leasing-steps')init
   WHERE category = @parent
   ORDER BY id DESC
   )cat
ORDER BY id ASC