在MySQL中从分层数据生成基于深度的树(无CTE)

31

大家好,我在MySQL上遇到一个问题,已经苦苦思索很多天了,但是还是无法解决。你们有什么建议吗?

基本上,我有一个类别表,其中包含如下域:idname(类别名称)和parent(该类别的父级ID)。

数据示例:

1  Fruit        0
2  Apple        1
3  pear         1
4  FujiApple    2
5  AusApple     2
6  SydneyAPPLE  5
....

有许多级别,可能超过3个级别。我想创建一个SQL查询,根据层次结构对数据进行分组:父级>子级>孙子级>等等。

它应该输出树形结构,如下所示:

1 Fruit 0
 ^ 2 Apple 1
   ^ 4 FujiApple 2
   - 5 AusApple 2
     ^ 6 SydneyApple 5
 - 3 pear 1

我能否使用单个SQL查询来完成这个任务?另一种我尝试过且可行的方法如下:

SELECT * FROM category WHERE parent=0

接下来,我再次遍历数据,并选择parent=id的行。这似乎是一个糟糕的解决方案。因为它是mySQL,所以不能使用CTE。


还在阅读和理解所有的解决方案,还不确定要选择哪个。 - bluedream
很遗憾你没有使用MSSQL - HierachyId功能可以解决这个问题,并且非常快。 - Kirk Broadhurst
1
https://dev59.com/hW855IYBdhLWcg3w_5cQ - orangepips
我在我的回答中添加了一些额外的信息 :) - Jon Black
4个回答

41

如果使用存储过程,你可以通过从PHP到MySQL的单个调用来完成:

示例调用

mysql> call category_hier(1);

+--------+---------------+---------------+----------------------+-------+
| cat_id | category_name | parent_cat_id | parent_category_name | depth |
+--------+---------------+---------------+----------------------+-------+
|      1 | Location      |          NULL | NULL                 |     0 |
|      3 | USA           |             1 | Location             |     1 |
|      4 | Illinois      |             3 | USA                  |     2 |
|      5 | Chicago       |             3 | USA                  |     2 |
+--------+---------------+---------------+----------------------+-------+
4 rows in set (0.00 sec)


$sql = sprintf("call category_hier(%d)", $id);

希望这能帮到你 :)

完整脚本

测试表结构:

drop table if exists categories;
create table categories
(
cat_id smallint unsigned not null auto_increment primary key,
name varchar(255) not null,
parent_cat_id smallint unsigned null,
key (parent_cat_id)
)
engine = innodb;

测试数据:

insert into categories (name, parent_cat_id) values
('Location',null),
   ('USA',1), 
      ('Illinois',2), 
      ('Chicago',2),  
('Color',null), 
   ('Black',3), 
   ('Red',3);

程序:

drop procedure if exists category_hier;

delimiter #

create procedure category_hier
(
in p_cat_id smallint unsigned
)
begin

declare v_done tinyint unsigned default 0;
declare v_depth smallint unsigned default 0;

create temporary table hier(
 parent_cat_id smallint unsigned, 
 cat_id smallint unsigned, 
 depth smallint unsigned default 0
)engine = memory;

insert into hier select parent_cat_id, cat_id, v_depth from categories where cat_id = p_cat_id;

/* http://dev.mysql.com/doc/refman/5.0/en/temporary-table-problems.html */

create temporary table tmp engine=memory select * from hier;

while not v_done do

    if exists( select 1 from categories p inner join hier on p.parent_cat_id = hier.cat_id and hier.depth = v_depth) then

        insert into hier 
            select p.parent_cat_id, p.cat_id, v_depth + 1 from categories p 
            inner join tmp on p.parent_cat_id = tmp.cat_id and tmp.depth = v_depth;

        set v_depth = v_depth + 1;          

        truncate table tmp;
        insert into tmp select * from hier where depth = v_depth;

    else
        set v_done = 1;
    end if;

end while;

select 
 p.cat_id,
 p.name as category_name,
 b.cat_id as parent_cat_id,
 b.name as parent_category_name,
 hier.depth
from 
 hier
inner join categories p on hier.cat_id = p.cat_id
left outer join categories b on hier.parent_cat_id = b.cat_id
order by
 hier.depth, hier.cat_id;

drop temporary table if exists hier;
drop temporary table if exists tmp;

end #

测试运行:

delimiter ;

call category_hier(1);

call category_hier(2);

使用Yahoo地理位置数据进行性能测试

drop table if exists geoplanet_places;
create table geoplanet_places
(
woe_id int unsigned not null,
iso_code  varchar(3) not null,
name varchar(255) not null,
lang varchar(8) not null,
place_type varchar(32) not null,
parent_woe_id int unsigned not null,
primary key (woe_id),
key (parent_woe_id)
)
engine=innodb;

mysql> select count(*) from geoplanet_places;
+----------+
| count(*) |
+----------+
|  5653967 |
+----------+

所以表中有560万行(地点),让我们看看从php调用的邻接列表实现/存储过程如何处理它。

     1 records fetched with max depth 0 in 0.001921 secs
   250 records fetched with max depth 1 in 0.004883 secs
   515 records fetched with max depth 1 in 0.006552 secs
   822 records fetched with max depth 1 in 0.009568 secs
   918 records fetched with max depth 1 in 0.009689 secs
  1346 records fetched with max depth 1 in 0.040453 secs
  5901 records fetched with max depth 2 in 0.219246 secs
  6817 records fetched with max depth 1 in 0.152841 secs
  8621 records fetched with max depth 3 in 0.096665 secs
 18098 records fetched with max depth 3 in 0.580223 secs
238007 records fetched with max depth 4 in 2.003213 secs

总体上,我对这些冷启动时间感到满意,因为我甚至不会考虑将成千上万行数据返回给我的前端,而是希望建立动态树,每次调用只获取几个层级。如果你认为innodb比myisam慢,那么你就错了——在我测试的所有方面,myisam的实现都比innodb慢两倍。

更多内容请参见:http://pastie.org/1672733

希望这可以帮到你 :)


我担心这种方法会有严重的性能问题。 - CyberDude
我正在尝试这种方法,写我的自己的方法,然后也许我会检查一下处理时间。 - bluedream
看起来不错,但我需要很长时间才能消化这个..无论如何谢谢..已点赞 - slier
1
很棒的解决方案。我稍微修改了一下,以支持构建名称的“完整路径”,并接受NULL id参数以打印所有父级及其子级。代码在https://gist.github.com/jdmullin/9377818。 - Jeremy Mullin
非常有用,且相对容易修改以适应我的需求 - 谢谢@JonBlack :) - Professor Abronsius
显示剩余4条评论

9

在关系型数据库中,存储分层数据有两种常见的方式:邻接列表(你正在使用的方式)和嵌套集合。在MySQL中管理分层数据这篇文章中对这些替代方案进行了非常好的阐述。只有使用嵌套集合模型才能在单个查询中完成所需操作。然而,嵌套集合模型使得更新分层结构更加繁琐,因此您需要根据您的操作要求考虑权衡。


3
您无法仅通过一个查询来实现此操作。在这种情况下,您的分层数据模型无效。我建议您尝试使用数据库中的两种存储分层数据的方式:MPTT模型和"lineage"模型。使用这些模型之一允许您在单个查询中执行所需的选择操作。
以下是有关此问题的更多详细信息的文章:http://articles.sitepoint.com/article/hierarchical-data-database

这里是关于层次模型的描述 - Ted Hopp
2
你为什么移除了 MySQL 标签? - Martin Smith
这不是针对MySQL的特定问题,而是一般的SQL主题。 - CyberDude
@CyberDude - 但是,如果例如OP在SQL Server上,这可以通过递归CTE实现。有人浪费时间提供了这样的答案,但当他们发现OP在MySQL上时就将其删除了。 - Martin Smith
6
@Martin:实际上,除了MySQL之外,所有其他主要的数据库管理系统都支持递归CTE。 - user330315

0

线性方式:

我正在使用一个丑陋的函数在一个简单的字符串字段中创建一棵树。

/              topic title
/001           message 1
/002           message 2
/002/001       reply to message 2
/002/001/001/  reply to reply
/003           message 3
etc...

该表可用于使用简单的SQL查询按树形顺序选择所有行:

select * from morum_messages where m_topic=1234 order by m_linear asc

INSERT 只需选择父线性(和子级),并根据需要计算字符串即可。

select M_LINEAR FROM forum_messages WHERE m_topic = 1234 and M_LINEAR LIKE '{0}/___' ORDER BY M_LINEAR DESC limit 0,1  
/* {0} - m_linear of the parent message*/

DELETE 操作很简单,可以删除消息,或者按线性方式删除所有父级回复。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接