gpt4 book ai didi

Mysql 按父子顺序

转载 作者:行者123 更新时间:2023-11-29 18:41:07 25 4
gpt4 key购买 nike

我想显示按父级排序,然后按子级排序的查询结果。这是我的代码

SELECT * FROM 
mst_category AS parent
LEFT JOIN mst_category AS child
ON child.category_parent = parent.category_id
GROUP BY parent.category_id
ORDER BY parent.category_group, COALESCE(parent.category_parent, parent.category_id), parent.category_parent != 0, child.category_id

查询结果:

query result

正如您所看到的,一些子项没有按父项 ID 排序。我的问题是如何排序?

最佳答案

将 order by 子句简化为您想要的排序顺序:

SELECT 
parent.category_id as `parent_id`,
parent.category_group as `parent_group`,
child.category_id as `child_id`
child.category_group as `child_group`
FROM mst_category AS parent
LEFT JOIN mst_category AS child
ON child.category_parent = parent.category_id
GROUP BY parent.category_id
ORDER BY parent.category_group, child.category_group

对于 3 个级别:

SELECT 
parent.category_id as `parent_id`,
parent.category_group as `parent_group`,
child.category_id as `child_id`
child.category_group as `child_group`,
child2.category_id as `child2_id`
child2.category_group as `child2_group`
FROM mst_category AS parent
LEFT JOIN mst_category AS child
ON child.category_parent = parent.category_id
LEFT JOIN mst_category AS child2
ON child2.category_parent = child.category_id
WHERE parent.category_id = 0
GROUP BY parent.category_id, child.category_id, child2_category_id
ORDER BY parent.category_group, child.category_group, child2.category_group

关于Mysql 按父子顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44932152/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com