码迷,mamicode.com
首页 > 数据库 > 详细

mysql 简单的sql优化示例[不定时更新]

时间:2017-04-04 17:51:12      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:脚本   union all   var   type   分析   sts   导致   简单   电话   

对于慢sql的分析步骤:
1) desc|explain sql 查看执行计划, 对于type很慢的, 分析是否建立了对应字段的索引
2) 进行排除法, 把子查询抽离出来, 单独执行,定位慢查询是哪个子查询导致的. 专门进行优化.
 
脚本:
CREATE TABLE stu (
id BIGINT(20) PRIMARY KEY AUTO_INCREMENT COMMENT ‘主键‘,
NAME VARCHAR(50) NOT NULL DEFAULT ‘‘ COMMENT ‘名称‘,
phone BIGINT(20) NULL COMMENT ‘电话‘,
UNIQUE KEY idx_phone (phone)
)ENGINE INNODB DEFAULT CHARSET utf8 COMMENT ‘测试_学生表‘;
 
CREATE TABLE course (
id BIGINT(20) PRIMARY KEY AUTO_INCREMENT COMMENT ‘主键‘,
NAME VARCHAR(50) NOT NULL DEFAULT ‘‘ COMMENT ‘名称‘
)ENGINE INNODB DEFAULT CHARSET utf8 COMMENT ‘测试_课程表‘;
 
CREATE TABLE stu_course (
id BIGINT(20) PRIMARY KEY AUTO_INCREMENT COMMENT ‘主键‘,
stu_id BIGINT(20) NOT NULL COMMENT ‘学生id‘,
cous_id BIGINT(20) NOT NULL COMMENT ‘课程id‘,
score INT(11) NOT NULL DEFAULT 0 COMMENT ‘分数‘,
KEY idx_stu_id (stu_id),
KEY idx_cous_id (cous_id)
)ENGINE INNODB DEFAULT CHARSET utf8 COMMENT ‘测试_学生课程关联表‘;
 
1. OR 变 UNION ALL
前:
SELECT id FROM stu WHERE id=10 OR id=20
后:
SELECT id FROM stu WHERE id=10
UNION ALL
SELECT id FROM stu WHERE id=20
 
2. IN (子查询) 变 INNER JOIN
前:
SELECT id FROM stu WHERE id IN (SELECT stu_id FROM stu_course)
后:
SELECT id FROM stu s
INNER JOIN (SELECT stu_id FROM stu_course) tmp ON s.id = tmp.stu_id
 
3. NOT IN (子查询) 变 LEFT JOIN
前:
SELECT id FROM stu WHERE id NOT IN (SELECT stu_id FROM stu_course)
后:
SELECT id FROM stu s
LEFT JOIN (SELECT stu_id FROM stu_course) tmp ON s.id = tmp.stu_id
WHERE tmp.stu_id IS NULL
 
4. IN 变 EXISTS
前:
SELECT id FROM stu WHERE id IN (SELECT stu_id FROM stu_course)
后:
SELECT id FROM stu s WHERE EXISTS (SELECT sc.stu_id FROM stu_course sc WHERE sc.stu_id = s.id)
 
 

mysql 简单的sql优化示例[不定时更新]

标签:脚本   union all   var   type   分析   sts   导致   简单   电话   

原文地址:http://www.cnblogs.com/duenboa/p/6665279.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!