I have 开发者_运维技巧an invitations
table in my database, which has got a from
and to
columns, which are both foreign keys for the userId
column in my users
table.
For example, if User # 1 invited User # 2 to do something, then in the invitations
table, from
will be 1, and to
will be 2.
I will use the to
column in where statements, such as:
SELECT * FROM invitations WHERE `to` = $currentUserId
But the from
column will never be used in WHERE statements.
From what I've read, you should only add an index on the columns which will be used in WHERE statements, however I've also read that you should always create Foreign keys.
Does it make sense for me to create an index on from
just to add a foreign key?
In the case of foreign keys, you should add one depending on what you do with users.
Internally, your fkeys will fire an action on any insert/update/delete of invitations, but also on any update/delete of users(id).
The first of these will use the index on users(id) to check if the user exists.
The other will essentially run a query that goes: do whatever you defined to do on update/delete from invitations where to/from = :id
.
So, if you change the id of users (very unlikely) you can make use of an index. And if you occasionally delete users (only slightly more likely), you can make use of the index.
And as point out in the other answer, indexes are also useful for queries with an order by/limit clause.
you should only add an index on the columns which will be used in WHERE statements
It is not so cut and dry. It is a good rule of thumb, but there is more to it than just this.
You should also index columns that you order by often and always, always test before and after a change to see if you have improved performance.
Foreign keys in general will not benefit from having an index defined on them, so long as they are not part of where/order by clauses. If they are, you should index them. (again, rules of thumb).
This looks like a good resource for optimizing MySQL - look towards the bottom where it explains about indexing.
精彩评论