关于MySQL的LIMIT 语法小优化!
来源:互联网 发布:ummy破解版for mac 编辑:程序博客网 时间:2024/06/05 00:57
转自: http://blog.csdn.net/yueliangdao0608/article/details/5530713
今天有朋友问起此类语句的优化,我大致给他介绍了下从SQL角度做简单的优化,至于应用程序方面的考虑咱暂时不考虑。
下面我来举一个 简单的例子。
考虑如下 表结构:
/*DDL Information For - t_girl.t_page_sample*/
----------------------------------------------
Table Create Table
------------- ----------------------------------------------------------------
t_page_sample CREATE TABLE `t_page_sample` (
`id` int(10) unsigned NOT NULL,
`v_state` tinyint(1) NOT NULL DEFAULT '1',
`log_time` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8
我的测试系统为标配DELL D630, XP系统。
示例表的记录数:
select count(*) from t_page_sample;
query result(1 records)
count(*)993098下面我们 来一步一步看看下面的这条语句:
explain select sql_no_cache * from t_page_sample order by id asc limit 900001,20;
query result(1 records)
idselect_typetabletypepossible_keyskeykey_lenrefrowsExtra1SIMPLEt_page_sampleALL(NULL)(NULL)(NULL)(NULL)993098Using filesort从 上面可以看出,她没有用到任何索引,扫描的行数为993098,而且用到了排序!
select sql_no_cache * from t_page_sample order by id asc limit 900001,20;
(20 row(s)returned)
(4688 ms taken)
那么我们怎么优化这条语句呢?
首先,我们想到的是索引。 在这条语句中,只有ID可能能用到索引,那么我们给优化器加一个暗示条件,让他用到索引。
select sql_no_cache * from t_page_sample force index (primary) order by id asc limit 900001,20;
(20 row(s)returned)
(9239 ms taken)
没想到用的时间竟然比不加索引还长。 看来这条路好像走不通了。
我们尝试着变化下语句如下:
select * from t_page_sample
where id between
(select sql_no_cache id from t_page_sample order by id asc limit 900001,1)
and
(select sql_no_cache id from t_page_sample order by id asc limit 900020,1);
(20 row(s)returned)
(625 ms taken)
哇,这个很不错,足足缩短了将近15倍!
那么还有优化的空间吗?
我 们再次变化语句:
select * from t_page_sample
where id >= ( select sql_no_cache id from t_page_sample order by id asc limit 900001,1)
limit 20;
(20 row(s)returned)
(406 ms taken)
时间上又比上次的语句缩短了1/3。可喜可贺。
上一篇:Shell读取用户输入
下一篇:在线生成一份经过专家优化的MySQL配置文件
- python 多进程之管道实例(模...
- 解决mysql“Access denied for...
- MySQL数据插入、修改、删除...
- mysql启动的四种方式
- 【原创】PostgreSQL 实现MySQL...
- linux dhcp peizhi roc
- 关于Unix文件的软链接
- 求教这个命令什么意思,我是新...
- sed -e "/grep/d" 是什么意思...
- 谁能够帮我解决LINUX 2.6 10...
- 关于MySQL的LIMIT 语法小优化!
- 关于MySQL的LIMIT 语法小优化
- 关于MySQL的LIMIT 语法小优化!
- 关于MySQL的limit优化
- MYSQL limit的优化
- MYSQL limit的优化
- MYSQL limit的优化
- mysql的limit优化
- mysql的limit优化
- mysql的limit优化
- MYSQL关于limit优化问题
- 关于mysql的limit
- 关于mysql 的limit
- limit是mysql的语法
- mysql的limit的优化
- mysql的limit的优化
- Mysql中limit的优化
- 优化mysql 的 limit offset
- android4.0 FragmentTabHost tabs在底部 仿qq界面
- 程序员生存定律--成长路上常见的坑
- error LNK2019: 无法解析的外部符号 "__declspec(dllimport)
- 集成电路的设计 —— 晶体管
- Shell读取用户输入
- 关于MySQL的LIMIT 语法小优化!
- 在线生成一份经过专家优化的MySQL配置文件
- 单机启动多个mysql服务(修改)
- AngularJS 表达式
- mysql主从备份Slave_IO_Running:No的解决方法
- 反射机制
- android drawable shape 的参数 和属性
- MFC CDialog
- 主从服务器上的命令,及状态信息