您正在谈论按父行对行集进行分组。
我知道如何在 MySQL 中执行此操作的唯一方法是使用GROUP_CONCAT()
不会按行对主题进行分组的函数,而是创建一个分组字符串。
以下是您可以执行的操作:
SELECT
a.id,
a.subject,
GROUP_CONCAT(CONCAT(b.id, ':::', b.subject) ORDER BY b.subject SEPARATOR '|||') AS subjectlist
FROM
subjects a
LEFT JOIN
subjects b ON a.id = b.parent_id
WHERE
a.parent_id = 0
GROUP BY
a.id,
a.subject
ORDER BY
a.subject
所以这会给你一个结果集,比如:
id | subject | subjectlist
---------------------------------------------------------------------
2 | subj1 | 23:::childsubj1|||28:::childsubj4
3 | subj2 | 18:::childsubj8|||55:::childsubj16
4 | subj3 | NULL
根据您在应用程序中使用的语言,您可以将字符串“分解”成数组,这些数组首先分隔每个主题,然后分隔该主题的 ID 和名称。subjects
|||
:::
显然,这样做的缺点是您必须确保您的子主题名称不包含您决定使用的分隔符或任何分隔符|||
。:::
编辑:实验上,我想出了这个替代解决方案,它可能更接近你正在寻找的东西:
尝试:
SELECT
c.subj,
c.id
FROM
(
SELECT
CONCAT('---> ', b.subject) AS subj,
b.id,
CONCAT(a.subject, b.subject) AS orderfactor
FROM
subjects a
INNER JOIN
subjects b ON a.id = b.parent_id
WHERE
a.parent_id = 0
UNION ALL
SELECT
subject AS subj,
id,
subject AS orderfactor
FROM
subjects
WHERE
parent_id = 0
) c
ORDER BY
c.orderfactor
此查询应为您提供以下结果:
subject | id |
----------------------------------------------------------
subj1 | 2 |
---> childsubj1 | 23 |
---> childsubj4 | 28 |
subj2 | 3 |
---> childsubj8 | 18 |
---> childsubj16 | 55 |
subj3 | 4 |
subj4 | 5 |
---> childsubj10 | 79 |