MySQL订单按父/子和名称

时间:2014-08-08 20:02:46

标签: mysql

如何使用MySQL查询表中的信息,以返回表中按类型名称和父类型排序的信息。

作为一个例子,我想拿一张像这样的表:

+---------+-------------+------------+
| type_id | parent_type | type_name  |
+---------+-------------+------------+
|       1 |           0 | Type 1     |
|       2 |           0 | Type B     |
|       3 |           0 | Type 3     |
|       4 |           3 | Sub Type 1 |
|       5 |           0 | Type 5     |
|       6 |           0 | Type 6     |
|       7 |           3 | Sub Type 2 |
|       8 |           0 | Type C     |
|       9 |           1 | Sub Type 1 |
+---------+-------------+------------+

然后使用查询将其拉出来:

+---------+-------------+------------+
| type_id | parent_type | type_name  |
+---------+-------------+------------+
|       1 |           0 | Type 1     |
|       9 |           1 | Sub Type 1 |
|       3 |           0 | Type 3     |
|       4 |           3 | Sub Type 1 |
|       7 |           3 | Sub Type 2 |
|       5 |           0 | Type 5     |
|       6 |           0 | Type 6     |
|       2 |           0 | Type B     |
|       8 |           0 | Type C     |
+---------+-------------+------------+

基本上使子行位于父行之后,并按类型名称对父进行排序。

到目前为止,这是我能够通过此查询得到的:

SELECT *
FROM `item_types` AS b 
ORDER BY
    CASE
        WHEN `parent_type` = 0
        THEN `type_id`
        ELSE `parent_type`
    END,
    type_name;

1 个答案:

答案 0 :(得分:0)

你有一个自我引用的表...所以你需要像

这样的东西
select id, parent_id, name
  from (select type_id as id, type_id as parent_id, type_name as name
          from item_types
         where parent_type = 0
        UNION
        select type_id as id, parent_type as parent_id, type_name as name)
          from item_types
         where parent_type != 0)
 order by id, parent_id, name