用户变量未在子查询中

时间:2019-02-22 12:14:54

标签: mysql mariadb recursive-datastructures

我在MariaDB上使用一条RECURSIVE语句,以便在我知道产品类别唯一ID时从自引用类别表中获取产品类别路径。

这有效:

WITH RECURSIVE categories AS (
        SELECT * FROM tbl_eav_categories tec2 WHERE tec2.category_id = 1023
        UNION
        SELECT tec3.* FROM tbl_eav_categories tec3, categories AS c WHERE tec3.category_id = c.parent_category_id
        )
        SELECT GROUP_CONCAT(CONCAT(category_default_label,' [',category_id,']') ORDER BY category_id ASC SEPARATOR ' >> ') FROM categories

并返回:

Consumables [7] >> Catering Equipment and Supplies [95] >> Tea Bags [1023]

太好了。

但是现在我需要列出所有类别ID,并在第二列中列出它们的路径。 我认为这只是在主类别表('tbl_eav_categories')表上执行SELECT并将上述查询作为子查询列放入即可。像这样:

SELECT
    @CatID := category_id AS 'cat_id',
    (
    WITH RECURSIVE categories AS (
        SELECT * FROM tbl_eav_categories tec2 WHERE tec2.category_id = @CatID
        UNION
        SELECT tec3.* FROM tbl_eav_categories tec3, categories AS c WHERE tec3.category_id = c.parent_category_id
        )
        SELECT GROUP_CONCAT(CONCAT(category_default_label,' [',category_id,']') ORDER BY category_id ASC SEPARATOR ' >> ') FROM categories
    ) 'categorypath'
FROM tbl_eav_categories;

但是,我得到的只是:

cat_id  categorypath
1   Bearings [1]
2   Bearings [1]
3   Bearings [1]
4   Bearings [1]
5   Bearings [1]
6   Bearings [1]
...

(像这样直到整个结果集的底部)。

经过研究,我确实认为它与@CatID变量在赋值之前被评估有关,但我无法解决该问题。

我在这里尝试遵循Ben English的指导:User variable in MySQL subquery,但它使我感到困惑:(

请帮助! :)

1 个答案:

答案 0 :(得分:0)

我相信我已经找到了答案,将整个表扫描包括在实际的CTE中:

WITH RECURSIVE category_path (id, title, path) AS
(
  SELECT category_id, category_default_label, category_default_label path FROM tbl_eav_categories WHERE parent_category_id IS NULL
  UNION ALL
  SELECT c.category_id, c.category_default_label, CONCAT(cp.path, ' [',c.parent_category_id, '] >> ', c.category_default_label) FROM category_path cp JOIN tbl_eav_categories c ON cp.id = c.parent_category_id
)
SELECT id,path FROM category_path
ORDER BY path;