树结构逆转(MySQL)

时间:2016-04-22 08:23:53

标签: mysql sql

我有一个以两种方式构建的类别树:每个类别都有一个路径和一个parentID。路径由类别的ID(从下到上)构成。 parentID引用另一个类别。所以我的表看起来像这样:

id | name        | path    | parentID
---+-------------+---------+---------
1  | Root        | NULL    | NULL
2  | Main        | NULL    | 1
3  | Electronics | |2|     | 2
4  | Computers   | |3|2|   | 3
5  | PCs         | |4|3|2| | 4
6  | Macs        | |4|3|2| | 4
7  | Cameras     | |3|2|   | 3
8  | Canon       | |7|3|2| | 7

现在我不需要类别' Root'和' Main'。我试图实现的是这样的输出:

id | resolved_path
---+-----------------------------
3  | Electronics
4  | Electronics_Computers
5  | Electronics_Computers_PCs
6  | Electronics_Computers_Macs
7  | Electronics_Cameras
8  | Electronics_Cameras_Canon

所以我有不同的深度,我需要按相反的顺序排列。我在网上找不到这个。我得到的就是这个片段,它显示了该类别的深度:

SELECT
*,
(ROUND(
     (LENGTH(cat.path) - LENGTH(REPLACE(cat.path, '|', ''))) / LENGTH('|')
) - 2) depth
FROM
    categories cat
WHERE
    cat.path IS NOT NULL

我不知道什么更容易:递归地通过parentID或对路径做一些魔术。

1 个答案:

答案 0 :(得分:0)

您可以使用此(未优化)功能作为基线:

DELIMITER //
DROP FUNCTION IF EXISTS extract_path //
CREATE FUNCTION extract_path(idlist VARCHAR(255))
RETURNS LONGTEXT
BEGIN
    DECLARE result LONGTEXT;
    DECLARE tmplist VARCHAR(255);
    DECLARE buffer VARCHAR(255);
    DECLARE lastpos INT;

    -- reverse and trim last separator (that first of reversed string)
    SELECT TRIM(BOTH FROM SUBSTRING(REVERSE(idlist), 2)) INTO tmplist;

    mainloop: LOOP
      -- split on separator
      SELECT LOCATE('|', tmplist) INTO lastpos;
      -- detect end
      IF lastpos IS NULL OR lastpos < 2
      THEN LEAVE mainloop;
      END IF;

      -- resolve next id
      SELECT cat.name INTO buffer
      FROM categories cat
      WHERE cat.id = TRIM(REVERSE(SUBSTRING(tmplist, 1, lastpos - 1)));

      -- append new element
      SELECT CONCAT(COALESCE(CONCAT(result, '_'), ''), buffer) INTO   result;

      -- prepare for next iteration
      SELECT TRIM(BOTH FROM SUBSTRING(tmplist, lastpos + 1)) INTO tmplist;

      -- detect end (corner case)
      IF tmplist IS NULL
      THEN LEAVE mainloop;
      END IF;

    END LOOP;

    RETURN result;
END //

SELECT extract_path('|1|2|3|');
-- with categories 1 -> foo ; 2 -> bar ; 3 -> baz
-- output is 'baz_bar_foo'
DELIMITER ;