如何使用MySQL COALESCE

时间:2018-07-18 22:36:23

标签: mysql coalesce

我有一个使用ID的父/子结构的旧表,我需要按父的名称对其进行排序,然后子级(父具有null parent_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

我已经修改了各种ORDER可能性,但无法获得所需的排序。任何指导表示赞赏。

表格行

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

1 个答案:

答案 0 :(得分:0)

您需要将表与自身连接起来,以便获得每个孩子的父母的名字,并以排序方式代替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

DEMO