Best SQL indexes for join table

前端 未结 2 730
迷失自我
迷失自我 2021-02-02 06:52

With performance improvements in mind, I was wondering if and which indexes are helpful on a join table (specifically used in a Rails 3 has_and_belongs_to_many context).

2条回答
  •  没有蜡笔的小新
    2021-02-02 07:28

    Depends on how you are going to query the data.

    Assuming you want to search for all of these...

    • WHERE bar_id = ?
    • WHERE foo_id = ?
    • WHERE bar_id = ? AND foo_id = ?

    ...then you should probably go with an index on {bar_id, foo_id} and an index on {foo_id}.

    While you could also create a third index on {bar_id}, the price of maintaining additional index would probably outweigh the benefit of better clustering in the smaller index.


    Also, how do you plan to cover your queries with indexes? Some of the alternatives, such as...

    • {foo_id, bar_id} and {bar_id}
    • {foo_id, bar_id} and {bar_id, foo_id}

    ...might cover certain kinds of queries better.

    Covering is a balancing act - sometimes adding a field to an index just for covering purposes is justified, sometimes it's not. You won't know until you measure on realistic amounts of data.

    (Disclaimer: I'm not familiar with Ruby. This answer is purely from the database perspective.)

提交回复
热议问题