MySQL: 多分组依据 Desc 顺序问题
MySQL: Multiple Group By With Desc Order Issue
我已经访问过 MySQL order by before group by 的 Single Group By,它工作正常。我对 2 组按列有疑问。
我下面 table 名为 "messages"。消息是用户帖子的评论
id | posts_id | from_user_id | to_user_id | message_description | created_at
-----------------------------------------------------------------------------
1 1 1 2 test1 2016-09-06 10:00:00
2 1 1 2 test2 2016-09-06 11:00:00
3 1 4 2 test3 2016-09-06 09:00:00
4 1 4 2 test4 2016-09-06 15:00:00
5 2 1 2 test1 2016-09-06 10:00:00
6 2 1 2 test2 2016-09-06 11:00:00
7 2 4 2 test3 2016-09-06 09:00:00
8 2 4 2 test4 2016-09-06 15:00:00
查询的结果输出应该是
id | posts_id | from_user_id | to_user_id | message_description | created_at
-----------------------------------------------------------------------------
2 1 1 2 test2 2016-09-06 11:00:00
4 1 4 2 test4 2016-09-06 15:00:00
6 2 1 2 test2 2016-09-06 11:00:00
8 2 4 2 test4 2016-09-06 15:00:00
我正在尝试检索 post 明智的和用户明智的他们的最新消息。
我在下面进行了尝试,但结果顺序不正确。
SELECT *
FROM messages
WHERE to_user_id = '2'
GROUP BY posts_id DESC,
from_user_id
ORDER BY id DESC
此问题与 SO 上发布的其他数千个问题相同。如手册中所述,最佳解决方案是不相关的子查询,例如:
SELECT x.*
FROM my_table x
JOIN
( SELECT MAX(id) id
FROM my_table
WHERE to_user_id = 2 -- OPTIONAL
GROUP
BY from_user_id
) y
ON y.id = x.id;
我已经访问过 MySQL order by before group by 的 Single Group By,它工作正常。我对 2 组按列有疑问。
我下面 table 名为 "messages"。消息是用户帖子的评论
id | posts_id | from_user_id | to_user_id | message_description | created_at
-----------------------------------------------------------------------------
1 1 1 2 test1 2016-09-06 10:00:00
2 1 1 2 test2 2016-09-06 11:00:00
3 1 4 2 test3 2016-09-06 09:00:00
4 1 4 2 test4 2016-09-06 15:00:00
5 2 1 2 test1 2016-09-06 10:00:00
6 2 1 2 test2 2016-09-06 11:00:00
7 2 4 2 test3 2016-09-06 09:00:00
8 2 4 2 test4 2016-09-06 15:00:00
查询的结果输出应该是
id | posts_id | from_user_id | to_user_id | message_description | created_at
-----------------------------------------------------------------------------
2 1 1 2 test2 2016-09-06 11:00:00
4 1 4 2 test4 2016-09-06 15:00:00
6 2 1 2 test2 2016-09-06 11:00:00
8 2 4 2 test4 2016-09-06 15:00:00
我正在尝试检索 post 明智的和用户明智的他们的最新消息。
我在下面进行了尝试,但结果顺序不正确。
SELECT *
FROM messages
WHERE to_user_id = '2'
GROUP BY posts_id DESC,
from_user_id
ORDER BY id DESC
此问题与 SO 上发布的其他数千个问题相同。如手册中所述,最佳解决方案是不相关的子查询,例如:
SELECT x.*
FROM my_table x
JOIN
( SELECT MAX(id) id
FROM my_table
WHERE to_user_id = 2 -- OPTIONAL
GROUP
BY from_user_id
) y
ON y.id = x.id;