How to properly index fields on a Rails join table migration?

前端 未结 2 540
误落风尘
误落风尘 2021-01-12 02:50

Rails 4 introduced a feature for generating join table migrations:

bin/rails generate migration CreateTeamsUsersJoinTable team user

This re

2条回答
  •  孤独总比滥情好
    2021-01-12 03:14

    To complete xlembouras answer, you make your choice based on how you query your table.

    For example, if you have a view that shows the users of a given team, the query will look like this :

    SELECT user.name FROM team_users tu 
    INNER JOIN users u 
    ON tu.user_id = u.id
    WHERE tu.team_id = X
    

    This benefits from t.index [:team_id, :user_id] but not t.index [:user_id, :team_id]

    The database will only use one index seek on the first index to retrieve the user ids

    If you have a view that shows the teams of a given user, the query would be something like the following :

    SELECT team.name FROM team_users tu 
    INNER JOIN team t 
    ON tu.team_id = t.id
    WHERE u.user_id = X
    

    This benefits from t.index [:user_id, :team_id] but not t.index [:team_id, :user_id]

    The database will only use one index seek on the first index to retrieve the team ids

    That's because of the way composed index are stored :

    index tree

提交回复
热议问题