Need two indexes on a HABTM join table?

前端 未结 3 1683
忘了有多久
忘了有多久 2021-01-31 15:37

A simple has_and_belongs_to_many association:

Person has_and_belongs_to_many :products
Product has_and_belongs_to_many :persons

Ar

3条回答
  •  走了就别回头了
    2021-01-31 16:14

    Yes they are helpful. But do you really need them? It all depends on what you're gonna do with it. Index on (person_id,product_id) will allow you to quickly find products belonging to person but will not help finding persons that own certain product. It will also enforce UNIQUE so you probably should use it. separate indexes on (person_id) and (product_id) will allow you to find both products belonging to person and persons that own certain product. Indices on (person_id,product_id) and (product_id,person_id) will work for both cases too and will be faster but will take more space and there will take a little bit (very little) more when inserting/updating rows. The time and space overhead is almost always worth it unless you have a base where you write more often than read. Personally I've seen Index Only Scans in 9.2 benefit greatly from two indexes on both columns. So you the real choice is between:

    unique index on (col 2, col 1), unique index on (col 1, col 2)

    and

    unique Index on (col 1, col 2), index on (col 2)

提交回复
热议问题