Rails 添加单列索引和联合索引 (迁移相关)
单列索引
add_index :users, :created_at
复合索引
add_index :orders, [:user_id, :user_type], :name => 'user_index'
索引的使用
模,数,空,运,最 ,快
- 模 糊查询
- 数 据类型错误
- 空 查询 null
- 运 算符 查询的字段使用了运算符
- 最 数据库索引最左 (联合索引遵循最左匹配原则)
- 快 如果数据库觉得全表扫描最快,就会进行全表扫描,就不会走索引了
为什么要使用联合索引
- 减少开销, 实际相当于建了(col1),(col1,col2),(col1,col2,col3)三个索引
- 效率高 假设每个条件可以筛选出10%的数据
索引筛选出1000w10% 10% *10%=1w 但是单个索引就是 100W
覆盖索引
直接通过遍历索引取得数据,而无需回表,这减少了很多的随机io操作 (如果一个索引包含所有需要的查询的字段的值,我们称之为覆盖索引)
总结postger单列索引失效的例子
- 类型转换
select * from products where item_id::VARCHAR = '1937'
- 对字段进行了计算
select * from products where item_id + 1 = '1938'
- 对字段使用函数
select * from products where abs(item_id) = '1938'
- 使用运算符
select * form users where organization_id > 1
- != 号
select * form users where organization_id != 1
- 使用not
select * from products where item_id is not null
select * from products where item_id not in (1937)
select * from products where item_id::VARCHAR NOT LIKE '%1'
- 模糊查询通配符在开头
select * from users where organization_id::VARCHAR like '%521' and name = '文文';