Mysql将父级和子级连接为字符串



这是我在mysql上的数据库,我需要提取连接所有父级和所有子级的内容。

id     | name             | parent_id | has_children
100017 | Roupas Femininas | 0         | 1
100018 | Meias            | 100017    | 1
100419 | Outros           | 100118    | 0
100418 | Meia calça       | 100118    | 0
100417 | Meias            | 100118    | 0
100117 | Tecidos          | 100017    | 1
100416 | Outros           | 100117    | 0
100413 | Lona             | 100117    | 0
100412 | Jeans            | 100117    | 0

我需要返回的示例:

Roupas Femininas > Meias > Outros
Roupas Femininas > Meias > Meia calça
Roupas Femininas > Meias > Meias
Roupas Femininas > Tecidos > Outros
Roupas Femininas > Tecidos > Lona
Roupas Femininas > Tecidos > Jeans

我如何从数据库中提取这些数据以获得该示例作为返回?

我一直在到处寻找,并在MySQL中阅读这些分层数据,但我没有找到我想要的结果。

我越来越接近预期的结果,但我无法确定问题所在。

SELECT CONCAT( REPEAT(' > ', COUNT(parent.nome_shopee) - 1), node.nome_shopee) AS name
FROM categoria_shopee_lista AS node,
categoria_shopee_lista AS parent
WHERE node.categoria_pai BETWEEN parent.categoria_pai AND parent.nome_shopee
GROUP BY node.nome_shopee
ORDER BY node.id;

结果:

>  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >Roupas Femininas
>  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >  >Outros
etc...

Mysql在线

这是正确的方法吗?

感谢

WITH RECURSIVE
cte AS (
SELECT *, name AS path
FROM test
WHERE NOT parent_id
UNION ALL
SELECT test.*, CONCAT_WS(' > ', cte.path, test.name)
FROM cte
JOIN test ON cte.id = test.parent_id
)
SELECT path
FROM cte
WHERE NOT has_children;
路径Roupas女性主义>Meias>OutrosRoupas女性主义>Meias>Meia calçaRoupas女性主义>Meias>迈亚斯Roupas女性主义>Tecidos>OutrosRoupas女性主义>Tecidos>LonaRoupas女性主义>Tecidos>牛仔裤

如果您知道最多有3个级别(不应该使用递归的级别深度不确定(,那么您就不需要链式查询了(只需要在下一个表上链式三次即可。parent_id=prev.id原则(:

SELECT
CONCAT(l1.name,
IF(l2.name IS NOT NULL,CONCAT(' > ',l2.name,''),
IF(l3.name IS NOT NULL,CONCAT(' > ',l3.name,''))
FROM categoria_shopee_lista l1
LEFT JOIN categoria_shopee_lista l2 ON l2.parent_id=l1.id
LEFT JOIN categoria_shopee_lista l3 ON l3.parent_id=l2.id
ORDER BY l1.name,l2.name,l3.name

相关内容

  • 没有找到相关文章

最新更新