Rails 添加单列索引和联合索引

单列索引

add_index :users, :created_at

复合索引

add_index :orders, [:user_id, :user_type], :name => 'user_index'

索引的使用

模,数,空,运,最 ,快

  1. 糊查询
  2. 据类型错误
  3. 查询 null
  4. 算符 查询的字段使用了运算符
  5. 数据库索引最左 (联合索引遵循最左匹配原则)
  6. 如果数据库觉得全表扫描最快,就会进行全表扫描,就不会走索引了

为什么要使用联合索引

  1. 减少开销, 实际相当于建了(col1),(col1,col2),(col1,col2,col3)三个索引
  2. 效率高 假设每个条件可以筛选出10%的数据
    索引筛选出1000w10% 10% *10%=1w 但是单个索引就是 100W

覆盖索引

直接通过遍历索引取得数据,而无需回表,这减少了很多的随机io操作 (如果一个索引包含所有需要的查询的字段的值,我们称之为覆盖索引)

总结postger单列索引失效的例子

  1. 类型转换
select * from products where item_id::VARCHAR = '1937'
  1. 对字段进行了计算
select * from products where item_id + 1 = '1938'
  1. 对字段使用函数
select * from products where abs(item_id) = '1938'
  1. 使用运算符
select * form users where organization_id > 1
  1. != 号
select * form users where organization_id != 1
  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'
  1. 模糊查询通配符在开头
select * from users where  organization_id::VARCHAR like '%521' and name = '文文';
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值