【问题标题】:SQL: Order by rowID and then by column based on the rowidSQL:按rowID排序,然后根据rowid按列排序
【发布时间】:2017-07-01 02:51:22
【问题描述】:

我有以下'departments' 表:

+-------+-------------+-------------------+
| rowid | department  | parent_department |
+-------+-------------+-------------------+
| 10    | Main Office | NULL              |
+-------+-------------+-------------------+
| 11    | Back Office | 10                |
+-------+-------------+-------------------+
| 12    | Commercial  | NULL              |
+-------+-------------+-------------------+
| 13    | Outdoor     | NULL              |
+-------+-------------+-------------------+
| 14    | Beach       | 13                |
+-------+-------------+-------------------+
| 15    | Gardening   | 13                |
+-------+-------------+-------------------+
| 16    | Accounting  | 10                |
+-------+-------------+-------------------+

我想根据 rowid 和 parent_department 来订购它:

+-------+-------------+-------------------+
| rowid | department  | parent_department |
+-------+-------------+-------------------+
| 10    | Main Office | NULL              |
+-------+-------------+-------------------+
| 11    | Back Office | 10                |
+-------+-------------+-------------------+
| 16    | Accounting  | 10                |
+-------+-------------+-------------------+
| 13    | Outdoor     | NULL              |
+-------+-------------+-------------------+
| 14    | Beach       | 13                |
+-------+-------------+-------------------+
| 15    | Gardening   | 13                |
+-------+-------------+-------------------+
| 12    | Commercial  | NULL              |
+-------+-------------+-------------------+

这样对于每个rowid,查找'parents_departments' 是否存在并按如下顺序显示。

请注意,我没有设计当前表格,遗憾的是我没有更改它的权限

【问题讨论】:

    标签: mysql sql database sorting sql-order-by


    【解决方案1】:

    试试这个:

    SELECT rowid, department, parent_department
      FROM departments
     ORDER BY IFNULL(parent_department, rowid), rowid;
    

    【讨论】:

    • @shmosel...不错的一个....但是我在我的本地和它的返回 rowid 上按顺序尝试了 10,11,16,12,13,14,15
    • @AnkitAgrawal 如果父组之间应该有任何排序,OP 没有指定它。我的假设是没关系。
    猜你喜欢
    • 2014-09-10
    • 2010-12-14
    • 2015-10-06
    • 2023-03-05
    • 1970-01-01
    • 2016-11-07
    • 1970-01-01
    • 1970-01-01
    • 2016-01-15
    相关资源
    最近更新 更多