作者:微信小助手
发布时间:2020-03-24T20:12:40
本文将结合实例 demo,阐述 30 条有关于优化 SQL 的建议,多数是实际开发中总结出来的,希望对大家有帮助。
1
反例子:
select * from employee;
正例子:
select id,name from employee;
只取需要的字段,节省资源、减少网络开销。
select * 进行查询时,很可能就不会使用到覆盖索引了,就会造成回表查询。
2
CREATE TABLE `employee` (
`id` int(11) NOT NULL,
`name` varchar(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`date` datetime DEFAULT NULL,
`sex` int(1) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
反例:
select id,name from employee where name='jay'
正例:
select id,name from employee where name='jay' limit 1;
加上 limit 1 后,只要找到了对应的一条记录,就不会继续向下扫描了,效率将会大大提高。
当然,如果 name 是唯一索引的话,是不必要加上 limit 1 了,因为 limit 的存在主要就是为了防止全表扫描,从而提高性能,如果一个语句本身可以预知不用全表扫描,有没有 limit ,性能的差别并不大。
3
新建一个 user 表,它有一个普通索引 userId,表结构如下:
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userId` int(11) NOT NULL,
`age` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `idx_userId` (`userId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
反例:
select * from user where userid=1 or age =18
正例:
//使用union all
select * from user where userid=1
union all
select * from user where age = 18
//或者分开两条sql写:
select * from user where userid=1
select * from