这里有很多类似的问题,但我认为没有充分回答这个问题.
我会从当前最流行的问题继续,并使用他们的例子,如果这没关系.
此实例中的任务是获取数据库中每个作者的最新帖子.
示例查询产生不可用的结果,因为它并不总是返回的最新帖子.
SELECT wp_posts.* FROM wp_posts
WHERE wp_posts.post_status='publish'
AND wp_posts.post_type='post'
GROUP BY wp_posts.post_author
ORDER BY wp_posts.post_date DESC
Run Code Online (Sandbox Code Playgroud)
目前接受的答案是
SELECT
wp_posts.*
FROM wp_posts
WHERE
wp_posts.post_status='publish'
AND wp_posts.post_type='post'
GROUP BY wp_posts.post_author
HAVING wp_posts.post_date = MAX(wp_posts.post_date) <- ONLY THE LAST POST FOR EACH AUTHOR
ORDER BY wp_posts.post_date DESC
Run Code Online (Sandbox Code Playgroud)
不幸的是,这个答案简单明了,并且在很多情况下产生的结果不如原始查询那么稳定.
我最好的解决方案是使用表单的子查询
SELECT wp_posts.* FROM
(
SELECT *
FROM wp_posts
ORDER BY wp_posts.post_date DESC
) AS wp_posts
WHERE wp_posts.post_status='publish'
AND wp_posts.post_type='post'
GROUP BY wp_posts.post_author
Run Code Online (Sandbox Code Playgroud)
我的问题是一个简单的问题: 无论如何在分组之前订购行而不诉诸子查询?
编辑:这个问题是另一个问题的延续,我的情况细节略有不同.您可以(并且应该)假设还有一个wp_posts.id,它是该特定帖子的唯一标识符.
我的桌子titles看起来像这样
id |group|date |title
---+-----+--------------------+--------
1 |1 |2012-07-26 18:59:30 | Title 1
2 |1 |2012-07-26 19:01:20 | Title 2
3 |2 |2012-07-26 19:18:15 | Title 3
4 |2 |2012-07-26 20:09:28 | Title 4
5 |2 |2012-07-26 23:59:52 | Title 5
Run Code Online (Sandbox Code Playgroud)
我需要按日期按降序排列的每个组的最新结果.像这样的东西
id |group|date |title
---+-----+--------------------+--------
5 |2 |2012-07-26 23:59:52 | Title 5
2 |1 |2012-07-26 19:01:20 | Title 2
Run Code Online (Sandbox Code Playgroud)
我试过了
SELECT *
FROM `titles`
GROUP BY `group`
ORDER BY MAX( `date` ) DESC
Run Code Online (Sandbox Code Playgroud)
但是我首先要从小组中得到结果.像这样
id |group|date |title
---+-----+--------------------+-------- …Run Code Online (Sandbox Code Playgroud) 我有一个mysql语句
SELECT *
FROM tbl_messages
WHERE to_user_id = '$user_id' OR from_user_id = '$user_id'
GROUP BY from_user_id
ORDER BY date_sent DESC
Run Code Online (Sandbox Code Playgroud)
并且它产生了正确的结果,但它们的顺序不正确.
分组效果很好,但是组中显示的记录是第一个记录在数据库中的记录,但我希望在每个组中显示最新记录.
有没有办法为每个组显示最新记录?
2011-12-19 12:16:25 This is the first message
2011-12-19 12:18:20 This is the second message
2011-12-19 12:43:04 This is the third message
Run Code Online (Sandbox Code Playgroud)
该组显示"这是第一条消息",我希望"这是第三条消息",因为这是最新的记录/消息.
干杯