gpt4 book ai didi

mysql - SQL嵌套排序依据?

转载 作者:可可西里 更新时间:2023-11-01 07:19:04 24 4
gpt4 key购买 nike

我确定以前有人问过这个问题,但我不知道如何准确调用它才能找到答案。

我有一个类别和子类别表。他们每个人都有一个 id 和一个 parent id。如果它是顶级类别,则父 id 为 0。子类别的父 id 设置为它的父类的类别 ID。

category_id          # The ID for this record
category_name # The name of the category
parent_id # The parent ID for this category
display_order # Order of categories within their grouping

1 A 0 0 # First primary category
2 a1 1 0 # Subcategory, parent is A, display_order is 0
3 a2 1 1
4 a3 1 2

5 B 0 1 # Second primary category
6 b1 5 0 # Subcategory, parent is B, display_order is 0
7 b2 5 1
8 b3 5 2

我正在尝试编写一个 SQL 查询,它将按以下顺序为我提供所有类别:

A, a1, a2, a3, B, b1, b2, b3

SELECT * FROM categories ORDER BY display_order 

这在 SQL 中可行吗,还是我需要使用多个查询

谢谢,布拉德

最佳答案

这样的事情可能会奏效:

SELECT *
FROM categories
ORDER BY IF(parent_id, parent_id, category_id), parent_id, display_order

但是因为它不能使用索引,所以它会很慢。 (虽然没有测试,可能是错误的)

第一个ORDER BY条件将 parent 和 child 放在一起;然后第二个确保父级在其子级之前;第三个将 children 自己分类。

此外,它显然只适用于您直接描述的情况,即您有两级层次结构。

关于mysql - SQL嵌套排序依据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8864397/

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