【发布时间】:2015-03-27 16:40:22
【问题描述】:
我有一张表,上面有以下字段
id, name, sub_id
1, test1, ""
2, test2, ""
3, test3, ""
4, test4, ""
5, test5, 1
6, test6, 1
7, test7, 2
8, test8, 3
我想从这个表中检索数据,排序方式是按 id 排序,如果存在则按 sub_id 排序。 例如:
id, name, sub_id
1, test1, ""
5, test5, 1
6, test6, 1
2, test2, ""
7, test7, 2
3, test3, ""
8, test8, 3
4, test4, ""
我试过 group by 和 order by 但没用。
【问题讨论】:
-
请尝试为分组字段使用别名。
-
我不认为您可以使用您的结构在单个查询中检索整个树结构(这就是您所拥有的):您可能会从以下资源中受益:mikehillyer.com/articles/managing-hierarchical-data-in-mysql