2013-03-28 69 views
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 
+1

_「按查詢順序發出」_是一個非常不好的標題。考慮到人們應該能夠搜索他們類似問題的答案。 _「問題」_根本不是描述。 – 2013-03-28 09:54:15

+0

深度第一,正確嗎? – didierc 2013-03-28 09:58:35

+0

@didierc是的,先深入排序。 – 2013-03-28 10:01:00

回答

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

+0

謝謝老闆,這對我有很大的幫助。謝謝你再次。 – 2013-03-28 10:36:05