2

我有一个基本上看起来像这样的模式:

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不为空,则应将其分组在其父级之下。

4

3 回答 3

2
SELECT * FROM `data` ORDER BY COALESCE(`parent`, `id`), `parent`, `id`
于 2012-04-03T20:34:18.797 回答
0

这是经过测试可在 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]
于 2012-04-03T20:31:04.790 回答
0

你说你想让它按标题排序,对吗?

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从查询中删除。

于 2012-04-03T20:39:56.237 回答