数据库索引

2017.12.16 - 南京 数据库

一.数据库索引失效的情况:

1.条件中使用or,会导致进行全表扫描,可以进行拆分然后union all:

select id from tableName where status='1' or status='2'
可以改为
select id from tableName where status='1'
union all
select id from tableName where status='2'

2.like查询是%开头的,会进行全表扫描

select id from tableName where name like '%中'
或
select id from tableName where name like '%中%'
可以改为
select id from tableName where name like '中%'

3.如果字段类型是字符串,则一定要在查询条件使用引号,否则不使用索引

select id from tableName where status=1
应改为
select id from tableName where status='1'

4.在索引列使用了函数或计算表达式:

select id from tableName where substring(name, 1, 3)='xxx';
select id from tableName where cast(id as varchar(100))='xxxxxxx';
select id from tableName where quantity/2=100;

5.使用!=和<>会使sql语句进行全表扫描,应避免使用

6.避免索引列有空值,如果有空值,语句中使用is null进行查询的时候会进行全表扫描

7.在where中不同列进行比较,会进行全表扫描

select id from tableName where quantity>num

8.基于cost成本分析(oracle因为走全表成本会更小):查询小表,或者返回值大概在10%以上

二.通用索引字段推荐:

1.主键(Primary Key)

2.外键(Foreign Key)

3.where字段

更新列表:

*

参考文章:

[2]:

相关阅读