如何使用mysql coalesce指定主排序顺序

jq6vz3qz  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(481)

我有一个旧表,它使用父/子结构和它的id,我需要按父表的名称排序,然后按子表排序(父表有 null 父项id)。
我已经能够使用下面所示的sql让它按子名称排序,但是无法让它对主数据库执行同样的操作( Cables 应该在之前 Cameras ).

SELECT a.id, a.parent_id,a.name
FROM `equipment` AS a
ORDER BY COALESCE(a.parent_id, a.id), a.parent_id IS NOT NULL, a.name

我已经修改了各种订购的可能性,但不能得到我需要的那种。感谢您的指导。
表行

id  | parent_id | name
--------------------------------
1   | null      | Cameras
2   | 1         | HandyCam 2000 5-50
3   | 1         | Netgear 360
4   | null      | Tripods
5   | 4         | Deluxe Tripod
6   | null      | Lighting
7   | 6         | Light Diffuser
10  | 6         | Really bright bulbs
11  | 1         | 16MM Handheld
12  | 6         | Big Lightbulb assembly
13  | 4         | HandyCam Stand
16  | 4         | My New Tripod
181 | null      | Cables

排序结果(仅对子级进行排序)

id  | parent_id | name
--------------------------------
1   | null      | Cameras
11  | 1         |    16MM Handheld
2   | 1         |    HandyCam 2000 5-50
3   | 1         |    Netgear 360
4   | null      | Tripods
5   | 4         |    Deluxe Tripod
13  | 4         |    HandyCam Stand
16  | 4         |    My New Tripod
6   | null      | Lighting
10  | 6         |    Really bright bulbs
12  | 6         |    Big Lightbulb assembly
7   | 6         |   Light Diffuser
181 | null      | Cables
8iwquhpp

8iwquhpp1#

您需要将表与其自身连接起来,这样就可以获得每个子表的父表名,并在排序中使用它而不是 COALESCE(a.parent_id, a.id) ```
SELECT a.id, a.parent_id,IF(a.parent_id IS NULL, a.name, CONCAT(' ', a.name)) AS name
FROM studio_tvs_equipment AS a
JOIN studio_tvs_equipment AS b ON IF(a.parent_id IS NULL, a.id = b.id, b.id = a.parent_id)
ORDER BY IF(a.parent_id IS NULL, a.name, b.name), a.parent_id IS NOT NULL, a.name

演示

相关问题