sql 1):
select id,goods_id,create_time,price from mkt_price_control
where 1=1 and price_id = 1 and goods_id = 598915619202568300
ORDER BY create_time desc
结果集 1):
sql 2): 当我们对上面的语句进行分组时, 出现了原先倒序排序失效的问题
select mpc1.* from (
select price,id,goods_id,create_time from mkt_price_control
where 1=1 and price_id = 1 and goods_id = 598915619202568300 ORDER BY create_time desc
) mpc1 GROUP BY mpc1.goods_id
结果集 2):
ps: 讲道理 group by 之后的结果应该取 2021-07-21 17:32:20 的那条数据才对, 但是为什么就没有效果呢?
需要告诉你的是, mysql 5.7 以上他不跟你讲道理
原因:
因为在mysql5.7中,系统会把order by优化掉。
在mysql5.7手册的8.2.2.1中有解释:
子查询的优化是使用半连接的策略完成的(The optimizer uses semi-join strategies to improve subquery execution)
使用半连接进行优化,子查询语句必须满足一些标准(In MySQL, a subquery must satisfy these criteria to be handled as a semi-join)。
其中一个标准是:必须不是一个包含了limit和order by的语句(It must not have ORDER BY with LIMIT.)
解决方法:
需要在我们 order by 的子查询中加上 limit 语句
来看看我们正确的sql语句是怎样写的:
select mpc1.* from (
select price,id,goods_id,create_time from mkt_price_control
where 1=1 and price_id = 1 and goods_id = 598915619202568300 ORDER BY create_time desc limit 999
) mpc1 GROUP BY mpc1.goods_id
使用 limit 后的结果集
看见这个结果, 正在阅读文章的你是不是直呼内行
最后别忘了给文章点赞收藏哦