mySQL hierarchical grouping sort

后端 未结 3 1040
暗喜
暗喜 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.

提交回复
热议问题