Hierarchical在不使用CTE查询的情况下获取所有父项

时间:2017-09-28 06:57:31

标签: mysql sql hierarchy

简介

有很多答案可以很好地解释如何从父子关系中读取分层数据。我正在使用mySQL,我创建了一个查询,该查询读取给定parent_id的所有父级(id)(通过逗号连接):

create table `menu` (
    `id` double ,
    `title` varchar (765),
    `controller` varchar (765),
    `method` varchar (765),
    `url` varchar (765),
    `parent_id` varchar (765),
    `added_date` datetime ,
    `updated_date` datetime 
);

填充表格的完整示例:http://sqlfiddle.com/#!9/48d276f/171。该查询应该没有CTE 运行,目前看起来像:

SELECT GROUP_CONCAT(T2.id) AS parents
FROM (
    SELECT
        @r AS _id,
        (SELECT @r := parent_id FROM menu WHERE id = _id) AS parent_id,
        @l := @l + 1 AS lvl
    FROM (SELECT @r := 31, @l := 0) vars, menu m
    WHERE @r <> 0) T1
JOIN menu T2
ON T1._id = T2.id
ORDER BY T1.lvl DESC;

查询结果为:

parents
-------------
3,17,31

挑战:

我想创建相同的查询,允许我阅读多个 id的父母。我认为子查询会有所帮助,但在将id传递给子查询时会出现错误(Unknown table 'T3' in field list)。

预期结果应为:

id      | parents
-----------------------
25      | 5,25
31      | 3,17,31
23      | 4,23

使用过的查询(http://sqlfiddle.com/#!9/48d276f/180):

SELECT T3.id, T4.parents
FROM menu T3, (SELECT T3.id, GROUP_CONCAT(T2.id) AS parents
  FROM (
      SELECT
          @r AS _id,
          (SELECT @r := parent_id FROM menu WHERE id = _id) AS parent_id,
          @l := @l + 1 AS lvl
      FROM (SELECT @r := T3.id, @l := 0) vars, menu m
      WHERE @r <> 0) T1
  JOIN menu T2
  ON T1._id = T2.id
  ORDER BY T1.lvl DESC) T4
WHERE T3.id IN (25, 31, 23)

1 个答案:

答案 0 :(得分:1)

您可以使用另一个连接应用与单个ID相同的逻辑,因此基本上会多次重复该评估。由于你不能再使用固定的起始值,我编码条件来重新初始化交叉连接中的变量(&#34; reset_r&#34;)。

尝试以下方法:

SELECT t1.id, GROUP_CONCAT(t1.r ORDER BY t1.lvl DESC) AS parents
FROM (
  SELECT
    t0.r_init AS id, 
    @r := IF(t0.reset_r = 1, t0.r_init, 
              (select parent_id from menu where id = @r)) AS r,
    @l := IF(t0.reset_r = 1, 1, @l + 1) AS lvl
  FROM 
    (SELECT m0.id as counter, m1.id AS r_init,
       ((SELECT min(id) FROM menu) = m0.id) AS reset_r 
     FROM menu m0, menu m1
     WHERE m1.id IN (25, 31, 23)
    ) t0 
  ORDER BY t0.r_init, t0.counter
) t1
WHERE t1.r <> 0
-- or instead of "where":
-- JOIN menu t2 ON t2.id = t1.r;
GROUP BY t1.id;

对于大型表格,您应该将p限制为树的最大深度,或使用different data model。此外,虽然您的表结构可能是一个示例,但您显然应该使用主键(否则父项和重置条件没有明确定义)和parent_id和{{1}的相同数据类型}。

更新:MySQL 5.6查询的一个版本(也适用于sql-fiddle),使用更多实现:

id