如何选择数据并获取层次结果

时间:2014-04-19 10:58:40

标签: mysql sql database

我有一个包含类别列表的表

表格结构

- ID
- category_name
- parent_category_ID // 0 indicates no parent

假设表格中包含以下数据

ID  | category_name | parent_category_ID
1   | verbs         | 0
2   | adjectives    | 0
3   | nouns         | 0
4   | go            | 1
5   | color         | 3
6   | bag           | 3
7   | good          | 2
8   | play          | 1
9   | polite        | 2
10  | t1            | 5
11  | t2            | 5
12  | t3            | 8

我希望结果按此顺序

ID  | category_name | parent_category_ID
1   | verbs         | 0
4   | go            | 1
8   | play          | 1
12  | t3            | 8
2   | adjectives    | 0
7   | good          | 2
9   | polite        | 2
3   | nouns         | 0
5   | color         | 3
10  | t1            | 5
11  | t2            | 5
6   | bag           | 3

将使结果显示为

verbs
--- go
--- play
--- --- t3
adjectives
--- good
--- polite
nouns
--- color
--- --- t1
--- --- t2
--- bag

我实际上不知道如何开始这样做,因为我的SQL经验仍然是初学者。

1 个答案:

答案 0 :(得分:1)

我不太确定我是否理解这一点但是试试这个:

SELECT 
      id, 
      category_name, 
      parent_category_ID
FROM  yourTableName
ORDER BY CASE 
WHEN parent_category_ID = 0 
THEN ID 
ELSE parent_category_ID END, id

演示:SQL FIDDLE