日期:2014-05-17  浏览次数:20457 次

【高分求助】根据条件查找最后一行数据的问题
max(id)和order by desc哪个效率更高?
还有没有其它的方法?

------解决方案--------------------
一直都是用order by的飘过。
------解决方案--------------------
如果 id 是主键,那么一样
否则若 id 有重复时,前者结果不一定对
------解决方案--------------------
我认为应该是order by,因为能够用到索引,而max是需要遍历比较的
------解决方案--------------------
探讨

如果 id 是主键,那么一样
否则若 id 有重复时,前者结果不一定对

------解决方案--------------------
探讨

如果 id 是主键,那么一样
否则若 id 有重复时,前者结果不一定对

------解决方案--------------------
第一条sql的explian是
1,"SIMPLE","collect","index",NULL,"PRIMARY","4",NULL,1,"Using index"


第二条sql
1,"SIMPLE",NULL,NULL,NULL,NULL,NULL,NULL,NULL,"Select tables optimized away"

------解决方案--------------------
探讨

引用:

如果 id 是主键,那么一样
否则若 id 有重复时,前者结果不一定对


测试了一下,的确没区别在速度上

PHP code

mysql_connect('127.0.0.1', 'root', 'root');
mysql_select_db('collect');

$sql1 = 'select id from collect order ……

------解决方案--------------------
id是primary key的吧?
innodb引擎的话order by limit 1效率会高些。
myisam下单纯select max(id)是很快的,最大id相当于存在一个缓存里,因为我explian语句发现Extra列显示的是Select tables optimized away,是和select count(id)一样的处理。
不过如果你除了max(id)还要select对应的其它字段,一条语句的效率可能就不如order by limit 1了,
当然你的语句可以变化为
select * from table where id = (select max(id) as id from table)
应该会非常快,是我基于explian的分析,你可以拿去测试下
自己多查看explian分析吧。

------解决方案--------------------
For explains on simple count queries (i.e. explain select count(*) from people) the extra section will read "Select tables optimized away." This is due to the fact that MySQL can read the result directly from the table internals and therefore does not need to perform the select.