sql优化

来源:互联网 发布:淘宝店铺后花园 编辑:程序博客网 时间:2024/06/07 16:27

sql优化
下面是做个记录
1 能用in的 不要用not in 不要用 != 不要用 not exist
select * from order where status!=0 and stauts!=1
not in/not exists都不是好习惯
可以优化为in查询:
select * from order where status in(2,3)
2 亲测 如果确定是返回只有一条数据 用 limit 1
[SQL]SELECT * FROM ph_member p where p.idCardNo = ‘340404198202171054’;
受影响的行: 0
时间: 0.069s
[SQL]
SELECT * FROM ph_member p where p.idCardNo = ‘340404198202171054’ LIMIT 1;
受影响的行: 0
时间: 0.048s
明显加了limit 1的更快。
3 尽量避免数据库用 null
应尽量避免在 where 子句中对字段进行 null 值判断,否则将导致引擎放弃使用索引而进行全表扫描,如:
select id from t where num is null
可以在num上设置默认值0,确保表中num列没有null值,然后这样查询:
select id from t where num=0
4 最好不要用or ,对于连续的数值,能用 between 就不要用 in 了。能用 between and 就用 between and 不用 in ,能用 in 就不用 not in 不用 or ,也不要用 union 。union最慢。
亲测如下
[SQL]SELECT * FROM ph_member_order_unline p where p.payType = 1 or p.payType = 2;
受影响的行: 0
时间: 0.892s
[SQL]
SELECT * FROM ph_member_order_unline p where p.payType in(1,2);
受影响的行: 0
时间: 0.498s
[SQL]
SELECT * FROM ph_member_order_unline p where p.payType =1 UNION ALL
SELECT * FROM ph_member_order_unline p where p.payType =2;
受影响的行: 0
时间: 0.999s
[SQL]
SELECT * FROM ph_member_order_unline p where p.payType BETWEEN 1 AND 2;
受影响的行: 0
时间: 0.457s
5 最好不要在where 里面使用函数。

6 能用exists 就不用 in 比如 下面
很多时候用 exists 代替 in 是一个好的选择:
select num from a where num in(select num from b)
用下面的语句替换:
select num from a where exists(select 1 from b where num=a.num)

7提一下
我们写代码最好把逻辑实现放在代码里。sql写的越简单越好,就让sql去做他自己最擅长的事情。