如何在 MYSQL 视图中使用递归

How to use recursion in MYSQL View

我有一个叫 categories 的 table。其中,包含三列:idparentIdnameparentId 列是引用同一 table.

id 列的外键

类别

| id | parentId | name      |
|----|----------|-----------|
|  1 |   NULL   | expense   |
|  2 |        1 | food      |
|  3 |        2 | grocery   |
|  4 |        3 | meat      |
|  5 |        3 | fruit     |
|  6 |        2 | dining    |

我想创建一个名为 categories_view 的视图,其中 returns categories table 并添加一个名为 path 的列,该列为其创建路径记录父路径(如果父路径不是 NULL)和 name.

的名称

categories_view

| id | parentId | name      | path                             |
|----|----------|-----------|----------------------------------|
|  1 |   NULL   | expense   | expense                          |
|  2 |        1 | food      | expense > food                   |
|  3 |        2 | grocery   | expense > food > grocery         |
|  4 |        3 | meat      | expense > food > grocery > meat  |
|  5 |        3 | fruit     | expense > food > grocery > fruit |
|  6 |        2 | dining    | expense > food > dining          |

如果我用 javascript 之类的东西来做这件事,我可以只递归,但我不确定如何在 SQL 视图中做到这一点。

您可以在视图中使用递归 CTE:

CREATE VIEW categories_view AS
WITH RECURSIVE cte AS (
    SELECT id, parentId, name, name AS path
    FROM categories
    WHERE parentId IS NULL
    UNION ALL
    SELECT c.id, c.parentId, c.name, CONCAT_WS(' > ', t.path, c.name)
    FROM categories c
    INNER JOIN cte t ON c.parentId = t.id
)

SELECT *
FROM cte
ORDER BY id;

这里有一个 demo 表明逻辑正在运行。