mySQL hierarchical grouping sort

后端 未结 3 992
暗喜
暗喜 2021-01-15 01:02

I have a schema that essentially looks like this:

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


        
相关标签:
3条回答
  • 2021-01-15 01:28

    You said you wanted it to sort on the titles, correct?

    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
    

    edit: Edited to remove type from the query.

    0 讨论(0)
  • 2021-01-15 01:30
    SELECT * FROM `data` ORDER BY COALESCE(`parent`, `id`), `parent`, `id`
    
    0 讨论(0)
  • 2021-01-15 01:37

    Here's a solution tested to work on SQL Server. Should be essentially the same on 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]
    
    0 讨论(0)
提交回复
热议问题