【问题标题】:Retrieving parent-child ordered data in MySQL在 MySQL 中检索父子有序数据
【发布时间】: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 但没用。

【问题讨论】:

标签: mysql hierarchy


【解决方案1】:

我花了一段时间才明白,sub_id 再次引用了同一个表。 之后我意识到你需要自己加入表格。

试试这个查询

SELECT
  a.*
FROM
  `some_table` AS a
  LEFT JOIN `some_table` AS b
    ON
      b.id = a.sub_id
ORDER BY
  IF (b.id IS NULL, 0, a.sub_id) ASC,
  a.id ASC

【讨论】:

    【解决方案2】:

    您的示例没有显示按 id 和 sub_id 排序,但如果您愿意,这样做会更容易:

    SELECT * FROM some_table ORDER BY id,ifnull(sub_id,0);
    

    我假设 "" 是一个空值,否则你需要一个与 ifnull 不同的函数。

    【讨论】:

      猜你喜欢
      • 2020-02-14
      • 2015-06-18
      • 1970-01-01
      • 1970-01-01
      • 2018-09-20
      • 1970-01-01
      • 2015-06-13
      • 1970-01-01
      • 2016-04-05
      相关资源
      最近更新 更多