我有下表: -
id name parent_id
1 ABC 0
2 XYZ 0
3 BB 1
4 AA 1
5 PQR 0
我想要这样的查询顺序显示这样的结果。
1 ABC 0
4 AA 1
3 BB 1
5 PQR 0
2 XYZ 0
即父项目和子项目按升序排列,父项目名称后跟子项目。
我使用这样的查询,但是当我们使用按级别排序时(没有升序)可以,但我想要带有名称的订单级别。
SELECT distinct `pp088_projects`.* , (
SELECT LPAD(parent.id, 5, '0')
FROM `pp088_projects` parent
WHERE parent.id = `pp088_projects`.id
AND parent.parent_id = 0
UNION
SELECT CONCAT(LPAD(parent.id, 5, '0'), '.', LPAD(child.id, 5, '0'))
FROM `pp088_projects` parent
INNER JOIN `pp088_projects` child
ON (parent.id = child.parent_id)
WHERE child.id = `pp088_projects`.id
AND parent.parent_id = 0
UNION
SELECT CONCAT(LPAD(parent.id, 5, '0'), '.', LPAD(child.id, 5, '0'), '.',
LPAD(grandchild.id, 5, '0'))
FROM `pp088_projects` parent
INNER JOIN `pp088_projects` child ON (parent.id = child.parent_id)
INNER JOIN `pp088_projects` grandchild ON (child.id = grandchild.parent_id)
WHERE grandchild.id = `pp088_projects`.id AND parent.parent_id = 0 ) AS level
FROM `pp088_projects` , `pp088_project_users`
WHERE (`pp088_projects`.`id` = `pp088_project_users`.`project_id`
AND `pp088_project_users`.`user_id` = '1')
AND (`pp088_projects`.`completed_on` = '0000-00-00 00:00:00')
ORDER BY level