gpt4 book ai didi

mysql - 在 mysql 中对结果进行分组和排序(具有层次信息的数据)

转载 作者:行者123 更新时间:2023-11-30 21:51:57 26 4
gpt4 key购买 nike

我有一个包含项目的表,有些是其他人的 child (我会说很像某种论坛对话,有些是以前的 child ,有些没有 child ,有些有很多 child 但只有一层深,没有 child 的 child ),例如,在使用某些条件查询后,我得到以下列表,按 id 排序:

| id  | title | date       | childof |
| 002 | tit2 | 2017-02-23 | 000 | if 000, not a child
| 003 | tit3 | 2017-05-12 | 000 | not a child
| 004 | tit4 | 2017-03-25 | 002 | child of 002
| 005 | tit5 | 2017-03-26 | 002 | other child of 002
| 006 | tit6 | 2017-06-13 | 000 | not a child
| 007 | tit7 | 2017-07-06 | 003 | only child of 003

我的问题是关于对结果进行排序/分组:我希望将结果列示如下:

| id  | title | date       | childof |
| 006 | tit6 | 2017-06-13 | 000 | no child most recent at first level
| 003 | tit3 | 2017-05-12 | 000 | one child
| 007 | tit7 | 2017-07-06 | 003 | only child of previous
| 002 | tit2 | 2017-02-23 | 000 | two children
| 004 | tit4 | 2017-03-25 | 002 | child #1 of 002 oldest
| 005 | tit5 | 2017-03-26 | 002 | child #2 of 002 most recent
  • 第一级(非子项目)按日期(最近的排在第一位)
  • children 在他们的 parent 之后重新分组,无论他们的日期是什么,但在 parent 之下从大到大排序

我的出发点是这样的:

SELECT * FROM mytable WHERE somecriteriaok ORDER BY date GROUP BY childof.

当然,我尝试了更复杂的解决方案,但似乎无法实现上述结果,所以我试图提出这个问题,试图让它变得简单明了……希望我成功了,并且会得到一些关于去哪里的提示(对不起我的英语...)。

皮埃尔。

最佳答案

虽然这有点棘手,但您可以做到,因为层次结构只有一层深。这是一种方法,使用 join:

SELECT t.*
FROM mytable t LEFT JOIN
mytable tp -- parent
ON tp.id = t.childof
WHERE somecriteriaok
ORDER BY COALESCE(tp.date, t.date) DESC, -- newest parents first
COALESCE(tp.id, t.id), -- keep records together
(tp.id IS NULL) DESC, -- put the parent first
t.date; -- children in date order

关于mysql - 在 mysql 中对结果进行分组和排序(具有层次信息的数据),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46865969/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com