【问题标题】:mySQL hierarchical grouping sortmySQL分层分组排序
【发布时间】:2012-04-04 04:39:56
【问题描述】:

我有一个基本上看起来像这样的架构:

CREATE TABLE `data` (
  `id` int(10) unsigned NOT NULL,
  `title` text,
  `type` tinyint(4),
  `parent` int(10)
)

type 字段只是一个枚举,其中 1 是父类型,2 是子类型(实际上有很多类型,其中一些应该表现得像父母,有些应该像孩子一样)。 parent 字段表示一条记录是另一条记录的子记录。

我知道这对于我想要构建的查询可能并不理想,但这是我必须使用的。

我想对数据进行排序和分组,以便父记录按title 排序,而在每个父记录下分组的是按title 排序的子记录。像这样:

 ID | title       |type |parent 
--------------------------------
 4  | ParentA     | 1   |
 2  | ChildA      | 2   | 4
 5  | ChildB      | 2   | 4
 7  | ParentB     | 1   |
 9  | ChildC      | 2   | 7
 1  | ChildD      | 2   | 7

** 编辑 **

我们应该能够将type 字段完全排除在外。如果parent 不为空,则应将其分组在其父级之下。

【问题讨论】:

  • 这是 2 级层次结构还是任意深度的树?
  • @Eric,只是一个简单的 2 级层次结构

标签: mysql


【解决方案1】:
SELECT * FROM `data` ORDER BY COALESCE(`parent`, `id`), `parent`, `id`

【讨论】:

  • 这看起来很干净......我不认为title 的排序要求可以用于 ORDER BY 子句吗?
  • 得到这个工作,感谢领导! ORDER BY COALESCE (IF(parentID, parentTitle, NULL), IF(ID, title, NULL)), parentID, title -- 在我的实际查询中工作,因为我有一个连接,它给了我 parentTitle,然后我可以在需要时交换到 COALESCE。
  • 抱歉,我没有注意到title 的要求。
  • 8 年后我才发现这个,h*ll 是如何工作的?!不过还是谢谢
【解决方案2】:

这是经过测试可在 SQL Server 上运行的解决方案。在 MySQL 上应该基本相同

select Id, Title, [Type], Id as OrderId from Hier h1 where [Type] = 1
union
select Id, Title, [Type], Parent as OrderId from Hier h2 where [Type] = 2
order by OrderId, [Type]

【讨论】:

    【解决方案3】:

    您说您希望它按标题排序,对吗?

    SELECT id, title, parent
    FROM
      ( SELECT id, title, parent,
        CASE WHEN parent is null THEN title ELSE CONCAT((SELECT title FROM `data` d2 WHERE d2.id = d.parent), '.', d.title) END AS sortkey
        FROM `data` d
       ) subtable
    ORDER BY sortkey
    

    编辑:已编辑以从查询中删除 type

    【讨论】:

    • 对该结果进行字符串连接和排序是相当低效的。
    猜你喜欢
    • 2013-03-28
    • 2020-05-16
    • 2017-08-11
    • 2012-01-27
    • 2016-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-21
    相关资源
    最近更新 更多