简体   繁体   English

MySQL查询,用于在具有GROUP_CONCAT的表中显示父子项

[英]MySQL query for showing parent child in a table with GROUP_CONCAT

We are building an application and client requirement is show child below each parent with a separator. 我们正在构建一个应用程序,并且客户要求在每个父母下方显示一个带有分隔符的孩子。

For eg: I have 2 tables as below 例如:我有2张桌子如下

category:             category_description:

id(PK) | parent_id    id(fk) | name
-------|----------    -------|--------
    1  |    0             1  | Fruits
    2  |    1             2  | Apple
    3  |    1             3  | Orange
    4  |    0             4  | Veggies
    5  |    4             5  | Tomatoes
    6  |    4             6  | Cucumber

and so on ...

The result should show in a table as below 结果应显示在下表中

ID | Name
---|-----
 1 | Fruits
 2 | Fruits > Apple
 3 | Fruits > Orange
 4 | Veggies
 5 | Veggies > Tomatoes
 6 | Veggies > Cucumber

and so on...

Even if the client inserts randomly, the result should show as above. 即使客户端随机插入,结果也应如上所示。

I have tried to execute the following query 我试图执行以下查询

SELECT c.category_id AS category_id, c.parent_id, c.sort_order, 
GROUP_CONCAT(cd.name SEPARATOR '  >  ') AS name FROM
category c LEFT JOIN category_description cd ON c.category_id = 
cd.category_id LEFT JOIN category_description cd1 ON cd1.category_id =
c.parent_id GROUP BY c.category_id, cd.name

But doesn't show the result as expected. 但未显示预期的结果。 Please let me know, where I am going wrong. 请让我知道,我要去哪里了。

Hope, I could explain it better. 希望我能更好地解释它。 Thanks in advance 提前致谢

I don't know why you are aggregating here; 我不知道你为什么在这里聚集; a join query should work, assuming there is only a single level hierarchy: 假设只有一个级别的层次结构,联接查询应该可以工作:

SELECT
    c.ID,
    CONCAT(CASE WHEN c.parent_id = 0 THEN cd1.name ELSE cd2.name END,
        CASE WHEN c.parent_id <> 0 THEN CONCAT(' > ', cd1.name) ELSE '' END) AS Name
FROM category c
LEFT JOIN category_description cd1
    ON c.id = cd1.id
LEFT JOIN category_description cd2
    ON c.parent_id = cd2.id
ORDER BY
    CASE WHEN c.parent_id = 0 THEN c.id ELSE c.parent_id END,
    c.parent_id;

    ID  Name
1   1   Fruits
2   2   Fruits > Apple
3   3   Fruits > Orange
4   4   Veggies
5   5   Veggies > Tomatoes
6   6   Veggies > Cucumber

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM