Rails Migration add_reference 多态联合索引问题

tinyfeng · March 18, 2019 · Last by tinyfeng replied at March 19, 2019 · 1183 hits

基于 ActiveRecord::Migration[5.2] 生成迁移文件

add_reference :products, :user, polymorphic: true, index: true

观察到,在 products 表生成的联合索引先通过 user_type,再通过 user_id 去查

user_type 区分度是很低的(对比 user_id),我感觉不如先根据 user_id 查。

rails 生成的索引,先根据区分度很低的 type 去查是有什么原因吗?

一是最左前缀原则。其次 就算数据库进行查询优化,也应该是先用 user_type 因为 user_type 比 user_id 可能的值少。这样你明白了吗?事实上建立联合索引的时候 必须需要考虑 最左前缀原则,值少的字段优先放在前面。

Reply to BruceDing

那其实是先根据区分度较低的字段来查,效率反而会高一些?学习了😅

不是先用 user_type 确定去那个表查吗?

Reply to w7938940

是根据 user 查 product,不是根据 product 查 user

You need to Sign in before reply, if you don't have an account, please Sign up first.