表 tcharge 数据200万条左右.
主键id,字段15个.目前无法添加索引.那么下面两条哪条会效率高一些,或者是说,有没有更好的办法让效率高一些,现在很慢.
1.
select statu_id from tcharge where phone=? and cash=? and time>? order by id desc
2.
select statu_id from (select phone,cash,time from tcharge order by id desc limit 300) where phone=? and cash=? and time>?
主键id,字段15个.目前无法添加索引.那么下面两条哪条会效率高一些,或者是说,有没有更好的办法让效率高一些,现在很慢.
1.
select statu_id from tcharge where phone=? and cash=? and time>? order by id desc
2.
select statu_id from (select phone,cash,time from tcharge order by id desc limit 300) where phone=? and cash=? and time>?
解决方案 »
- 【急!!!】应用程序安装后,如何找到他对应的mysql的database?
- mysql root账户登录user表是只读的,怎么修改啊?
- 这个sql语句怎么写???
- 请大家看一下,我这两个sql语句的效率问题
- mysql创建触发器的奇怪问题
- MYSQL如果搞个自动累加的虚拟字段?
- ms sql存储过程向mysql存储过程转化的问题
- mysql用SQL如何实现插入数据时,如果数据已经存在就更新?
- mysql 支持 SELECT TOP 2 * FROM testtable 吗?
- MySQL client run out of memory是怎样产生的?
- 不重启mysql实现与os的时间保持一致
- 建立触发器的问题。
后面我就直接查300条以内的了.基本上是一样的.
对了第二条写错了.应该是:
2.
select statu_id from (select statu_id,phone,cash,time from tcharge order by id desc limit 300) where phone=? and cash=? and time>?
explain select statu_id from (select statu_id,phone,cash,time from tcharge order by id desc limit 300) where phone=? and cash=? and time>?贴一下结果。
一个查询快不快,首先看你遍历了多少行数据;
先不用看explain,从数据库干的事情来理解就知道第一条语句,其中有where子句,而且因为你的where子句列出的字段,没有一个字段有索引,所以会遍历所有200W条记录中挑出满足记录的行,然后再按id做排序,因为id有索引,所以时间消耗在挑记录上第二条,虽然是两个语句,但是外层的时间基本可以忽略了,因为是从内层的300行中查询
内层,按id排序,id有索引,然后只要前300行,那么遍历的行就是300行(关于limit扫描表的行数,看mysql手册关于limit的说明)再通过explain验证
第一条的rows项的值肯定是表的总行数;
第二条,外层语句rows项是300,内层虽然也是总数,但是基于mysql的limit优化,实际rows是300;所以按照扫描表的行数来说,第二条肯定快过第一条;