我有下表: -
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
答案 0 :(得分:1)
由于您只有两个级别的深度,因此不需要递归(MySQL支持有限);而只是按id
排序:
SELECT *
FROM pp088_projects
ORDER BY IF(parent_id, parent_id, id), parent_id, id
在sqlfiddle上查看。
或者,如果您想按名称订购:
SELECT child.*
FROM pp088_projects child
LEFT JOIN pp088_projects parent ON child.parent_id = parent.id
ORDER BY COALESCE(parent.name, child.name), parent.id, child.name
在sqlfiddle上查看。