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
· 检查语句中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
相关文章推荐
- SQL SERVER数据库状态(脱机,联机,可疑)及SQL设置语句详解
- 对B+树与索引在MySQL中的认识
- sqlite3数据库优化处理
- pl/sql创建并使用存储过程
- 【SQL查询日志】查看数据库历史查询记录
- iOS FMDB数据库的增删改查
- MYSQL卸载后重新安装最后无法start service的解决办法
- [Phonegap+Sencha Touch] 移动开发78 Sqlite(websql)出错:too many SQL variables 的解决办法
- 第一篇 mysql安装
- Oracle 110个常用函数
- navicat工具来将SQL Server数据迁移到MySQL
- oracle数据库-10G客户端导出11G数据文件,空表不能导出
- MemCache超详细解读
- 淘宝海量数据库OceanBase:系统架构详解
- SQL Server安全(8/11):数据加密(Data Encryption)
- 快速查看数据库内库、表大小
- mysql蠕虫复制
- django之创建第8-1个项目-数据库之增删改查/数据库数据显示在html页面
- c#使用SQLiteDataAdapter配合DataGridView增删改查数据
- 全文搜索引擎coreseek安装配置(sphinx)