MySql:需要 SQL 查询来按某些规则对表中的记录集进行排序和分组

标签 mysql sql sorting grouping

在 MySql 中我有表:

idPost | idPostParent | postText                              | dateCreated         |
1      | 1            |  This is parent post no1              | 2012-01-01 12:00:00 |
2      | 2            |  This is parent post no2              | 2012-01-02 13:00:00 |
3      | 1            |  This is first reply on idPost:1      | 2012-01-02 13:30:00 | 
4      | 4            |  This is parent post no3              | 2012-01-04 10:00:00 |
5      | 2            |  This is first reply on idPost:2      | 2012-01-04 11:00:00 |
6      | 1            |  This is second reply on idPost:1     | 2012-01-05 15:00:00 |
7      | 2            |  This is second reply on idPost:2     | 2012-01-06 17:00:00 |

注意:

  1. 如果 idPost = idPostParent,则检测到父帖子
  2. 如果 idPost <> idPostParent 并且回复是 与 idPostParent 中的帖子相关

需要 SQL 查询来根据某些规则对表中的记录集进行排序和分组:

  1. 帖子必须按 idPostParent 分组(先是父帖子,然后是它的帖子 回复)
  2. 最新输入的 PARENT 帖子或最近输入的回复必须在顶部。

结果集应该是:

idPost | idPostParent | postText                              | dateCreated         |
2      | 2            |  This is parent post no2              | 2012-01-02 13:00:00 |
5      | 2            |  This is first reply on idPost:2      | 2012-01-04 11:00:00 |
7      | 2            |  This is second reply on idPost:2     | 2012-01-06 17:00:00 |
1      | 1            |  This is parent post no1              | 2012-01-01 12:00:00 |
3      | 1            |  This is first reply on idPost:1      | 2012-01-02 13:30:00 |
6      | 1            |  This is second reply on idPost:1     | 2012-01-05 15:00:00 |
4      | 4            |  This is parent post no3              | 2012-01-04 10:00:00 |

原因: 父帖子 idPost=2 有最新输入的回复帖子,因此它的线程必须在表格的顶部。

感谢任何可能为解决方案做出贡献的人!

最佳答案

这适用于您的测试数据

SELECT
posts.*
FROM posts
INNER JOIN 
  (
    SELECT idPostParent, MAX(dateCreated) as dateLastAnswer
    FROM posts
    GROUP by idPostParent
  ) AS pp ON posts.idPostParent=pp.idPostParent
ORDER BY pp.dateLastAnswer DESC, idPost ASC

关于MySql:需要 SQL 查询来按某些规则对表中的记录集进行排序和分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9254266/

相关文章:

php - 我的 php 代码只将我的 csv 文件的第一行导入到数据库

c++ - MATLAB 中的 mysql.cpp 编译错误

mysql数据类型用于存储包含转义序列的文本(代码)

php - XAMPP : mySQL is not connecting

sql - SQL 中日期的模运算

mysql - 通过计数(不同)优化查询

ios - 如何整理NSArray仅获取具有特定字符串的内容

php - 如何防止 PHP 中的 SQL 注入(inject)?

ruby - 使用 Ruby 中的属性对对象列表进行排序

php - 对多个值进行排序 MYSQL Laravel