在做站内信的功能时,需要将某个用户和其他用户的站内信取出,并且和每个用户的会话只展示最新的一条,在编写sql语句的时候遇到问题。
问题:group by 子查询中order by无效
消息message表如下
sql语句
select *,count(id) cnt from (select * from message order by id desc) tt
group by conversation_id;
由于要取出每个conversation会话的最新记录,子查询中使用order by语句,但是结果并未生效。根据create_date观察,取出的to_id为1的message并不是最新的,子查询中的order by未生效。
网上查阅博客得知,是因为mysql 5.7版本对这个查询进行优化了,认为子查询中的order by可以进行忽略,只要Derived table里不包含如下条件就可以进行优化:
- UNION clause
- GROUP BY
- DISTINCT
- Aggregation
- LIMIT or OFFSET
详细介绍链接:https://yq.aliyun.com/articles/72503
解决办法:
通过limit 语句使子查询的order by生效
select *,count(id) cnt from (select * from message order by id desc limit 0,10) tt
group by conversation_id ;