sql规范
文章目录
尽量避免在where 语句中使用or
反例:
select worker_name,dept_id,age from tbl_hr_worker where dept_id = 223 or age =36
正例
select worker_name,dept_id,age from tbl_hr_worker where dept_id = 223
union all
select worker_name,dept_id,age from tbl_hr_worker where age = 36
理由
使用or 可能灰使索引失效,从而全表扫面,对于or + 没有索引的字段,当查询走到没有索引的字段会执行全表扫描
union 和 union all 联合查询
用于合并两个或多个select 语句的结果集
【注意】 union 内部的select 语句必须有相同数量的列,列必须拥有相似的数据类型,同时,每条select 语句中的列顺序必须相同,才能联合查询
【不同点】 union 操作符只会选取不同的结果集,如果需要允许重复的值,需要使用union all
如果查询结果只有一条或者只需要一条记录(可能最大/小值),建议使用 limit 1
create table 'student' (
'id' int(11) not null,
'name' varchar(50) default null,
'age' int(11) default null,
'date' datetime default null,
'sex' int(1) default null,
primary key ('id')
) engine=innodb default charset=utf8mb4;
反例:
select id,name from student where name='Tom'
正例
select id,name from employee where name='Tom' limit 1;
尽量用 union all 替换 union
如果检索结果中不会有重复的记录,推荐 union all 替换 union
反例:
select * from user where userid = 1
union
select * from user where age = 20
正例:
select * from user where userid = 1
union all
select * from user where age = 20
理由
如果使用union,不管检索结果有没有重复,都会尝试进行合并,然后在输出最终结果前进行排序。
如果已知检索结果没有重复记录,使用 union all 代替 union,这样会提高效率。
where子句中考虑使用默认值代替 null
反例
select user_id, name, age from user where age is not null;
正例
– 表字段 age 设置0为默认值代替null
select user_id, name, age from user where age > 0;
理由:
并不一定使用 is null 或 is not null 就会不走索引了,这个跟mysql版本以及查询成本都有关。
如果mysql优化器发现,走索引比不走索引成本还要高,肯定会放弃索引,这些条件 !=,<> ,isnull,is not null 经常让索引失效,其实是因为一般情况下,查询的成本高,优化器自动放弃索引的。
以及查询成本都有关。
如果mysql优化器发现,走索引比不走索引成本还要高,肯定会放弃索引,这些条件 !=,<> ,isnull,is not null 经常让索引失效,其实是因为一般情况下,查询的成本高,优化器自动放弃索引的。
如果把 null 值,换成默认值,很多时候让走索引成为可能,同时,表达意思会相对清晰一点。