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
_「按查詢順序發出」_是一個非常不好的標題。考慮到人們應該能夠搜索他們類似問題的答案。 _「問題」_根本不是描述。 – 2013-03-28 09:54:15
深度第一,正確嗎? – didierc 2013-03-28 09:58:35
@didierc是的,先深入排序。 – 2013-03-28 10:01:00