MySQL按排序字段值排序父/子

时间:2014-06-12 10:24:39

标签: mysql

我已经建立了父子关系表(Sections / Subsections或Categories.Subcategories)。我想先按父母' SectionSort'然后是儿童' SectionSort '字段。

示例表:

IDSection | SectionParentID | SectionSort | SectionName
-------------------------------------------------------
 2        |        0        |      2      | Chapter 2         
 1        |        0        |      1      | Chapter 1
 5        |        1        |      1      | Subchapter 1
 4        |        1        |      3      | Subchapter 3
 3        |        1        |      2      | Subchapter 2
 7        |        2        |      2      | Sunchapter 5
 6        |        2        |      1      | Subchapter 4

' SectionSort'根据用户需要,可以通过上下移动到列来动态更改。

我需要得到以下结果:

IDSection | SectionParentID | SectionSort | SectionName
-------------------------------------------------------
 1        |        0        |      1      | Chapter 1         
 2        |        0        |      2      | Chapter 2
 3        |        1        |      1      | Subchapter 1 
 4        |        1        |      2      | Subchapter 2
 5        |        1        |      3      | Subchapter 3
 6        |        2        |      1      | Sunchapter 4
 7        |        2        |      2      | Subchapter 5

或类似的东西:

Chapter 1
 -Subchapter 1
 -Subchapter 2
   -..... 
 -SubChapter 3
Chapter 2
 -Subchapter 4
 -Subchapter 5

这是我尝试但仅适用于下一级而不是3~n:

SELECT EvalQuestions.*, Child.SectionSort AS Child_SectionSort, Parent.SectionParentsIDs AS Parent_SectionParentsIDs, Parent.SectionParentNames AS Parent_SectionParentNames,
Parent.SectionName AS Parent_SectionName, Parent.SectionSort AS Parent_SectionSort, Parent.SectionParentID AS Parent_SectionParentID 
FROM EvalQuestions INNER JOIN (EvalSections Parent INNER JOIN EvalSections Child ON
Parent.SectionParentID = Child.IDSection) ON
EvalQuestions.SectionID = Parent.IDSection 
ORDER BY Parent.SectionSort, Child.SectionSort, QuestionSort

1 个答案:

答案 0 :(得分:0)

试试这个。

select * from Table order by SectionParentID asc,SectionSort asc.