0

我有一个包含以下列的用户表:

  • ID
  • 姓名
  • parent_id
  • 等级

我想订购这张桌子作为祖先(https://github.com/stefankroes/ancestry)。没有在用户表中添加祖先列,有没有办法在Mysql中创建临时祖先列。

[更新]

我想列出按临时列祖先排序的 mysql 中的用户,这些祖先应该根据其“parent_id”对每个用户层次结构具有价值。

4

1 回答 1

0

看看下面的文章......我认为这正是你要找的:

http://explainextended.com/2009/03/19/hierarchical-queries-in-mysql-adding-ancestry-chains/

这描述了如何制作/使用分层查询来获取树结构中节点的祖先。

更新

由于您的级别数量有限,因此像下面这样的查询可以完成这项工作。下面的查询是针对 7 个级别的,尽管它需要优化,因为它是一个工作粗略/草稿。

select
SUBSTRING_INDEX(SUBSTRING(ancestry, 1, CHAR_LENGTH(ancestry) - 1), ',', -1) as ID,
SUBSTRING(ancestry, 1, CHAR_LENGTH(ancestry) - 1) as Ancestry
from
(
  select 
  concat(
  IF(NOT u1.id IS NULL,concat(u1.id,','),''),
  IF(NOT u2.id IS NULL,concat(u2.id,','),''),
  IF(NOT u3.id IS NULL,concat(u3.id,','),''),
  IF(NOT u4.id IS NULL,concat(u4.id,','),''),
  IF(NOT u5.id IS NULL,concat(u5.id,','),''),
  IF(NOT u6.id IS NULL,concat(u6.id,','),''),
  IF(NOT u7.id IS NULL,concat(u7.id,','),''),
  IF(NOT u8.id IS NULL,concat(u8.id,','),'')
  ) as ancestry
  from User u1 
  left join User u2 on u1.id = u2.parent_id
  left join User u3 on u2.id = u3.parent_id
  left join User u4 on u3.id = u4.parent_id
  left join User u5 on u4.id = u5.parent_id
  left join User u6 on u5.id = u6.parent_id
  left join User u7 on u6.id = u7.parent_id
  left join User u8 on u7.id = u8.parent_id
)
as ancestryTable;

SQLFiddle:http ://sqlfiddle.com/#!2/93c1f/46

更新 - 优化版本和更正

select ID, ancestry
from
(
  select 
  u8.ID as ID,  
    concat(
    IF(u1.id IS NULL,'', IF(u2.id IS NULL,u1.id,concat(u1.id,','))),
    IF(u2.id IS NULL,'', IF(u3.id IS NULL,u2.id,concat(u2.id,','))),
    IF(u3.id IS NULL,'', IF(u4.id IS NULL,u3.id,concat(u3.id,','))),
    IF(u4.id IS NULL,'', IF(u5.id IS NULL,u4.id,concat(u4.id,','))),
    IF(u5.id IS NULL,'', IF(u6.id IS NULL,u5.id,concat(u5.id,','))),
    IF(u6.id IS NULL,'', IF(u7.id IS NULL,u6.id,concat(u6.id,','))),
    IF(u7.id IS NULL,'', IF(u8.id IS NULL,u7.id,concat(u7.id,','))),
    IF(u8.id IS NULL,'',u8.id)
    )as ancestry, 
     u1.id as a1,  u2.id as a2,  u3.id as a3,  u4.id as a4,
     u5.id as a5,  u6.id as a6,  u7.id as a7,  u8.id as a8
    from User u1 
    right join User u2 on  u2.parent_id = u1.id
    right join User u3 on  u3.parent_id = u2.id
    right join User u4 on  u4.parent_id = u3.id
    right join User u5 on  u5.parent_id = u4.id
    right join User u6 on  u6.parent_id = u5.id
    right join User u7 on  u7.parent_id = u6.id
    right join User u8 on  u8.parent_id = u7.id       
) as Ancestry
order by ancestry.ancestry

JSFiddle:http ://sqlfiddle.com/#!2/93c1f/105

于 2013-10-01T11:08:52.187 回答