0

我有下表: -

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
4

1 回答 1

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上查看。

于 2013-03-28T10:19:25.910 回答