您的位置:首页 > 数据库

sql 优化方案

2016-04-05 14:55 204 查看
· 检查 where 及 order by 涉及的列上是否建立索引,避免全表扫描。

· 检查语句中select * 是否真的需要全部字段信息,只输出需要的列。

· 应尽量避免在 where 子句中使用 or 来连接条件,否则将导致引擎放弃使用索引而进行全表扫描,可以用 union all 替换。比如select id from t where num=10 or num=20 可用 select id from t where num=10 union
all select id from t where num=20 替换。

· order by 实现全局排序,如果没有特殊要求,尽量不要在语句中使用排序。如果是热数据,可以考虑放到redis order set中。

· 合理使用union all替代union。union在合并两个结果集时会自动去重,会消耗很大资源。 同时先进行数据过滤,减少后续处理的记录数。 比如两个大表关联,可以通过条件将缩小结果集,然后再进行关联。

· 合理使用 group by 代替 distinct。比如select distinct num from a 可改成select num from a group by num。

· 检查 where 子句中判断时间范围。根据业务场景考虑按照时间分表分区,查询时只读取满足分区的数据。

· in 和 not 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)。

· 尽量用join替代子查询。比如select num from a where num in(select num from b) 可用 select num from a left join b on a.num=b.num。

需要说明一点,不是所有查询都要走索引。当查询的数据集超过记录总数的30%,使用全表扫描要比走索引要更有优势。

基于不同的查询条件,数据表上会建立多个索引。索引的选择可以通过Selectivity(选择性)这一指标衡量。Selectivity越趋近于1使用索引越合理,就像聚集索引。

★ db 运算 转为 应用运算,大sql 从业务上拆分为多个小sql
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: