问题
I checked this SO post:
What's the difference between primary key, unique key, and index in MySQL?
and found the statement:
Also note that columns defined as primary keys or unique keys are automatically indexed in MySQL.
Based on this, I have two questions:
- Am I safe in assuming that there is no performance benefit to creating an index on a primary key itself because the primary key, by design, is an index?
Perhaps the more important question:
- If you are doing the classic example people cite, doing SELECT based on lastName and firstName, and that table has a primary key that you SELECT by frequently as well, would you create the index as (primary_key, lastName, firstName) or just (lastName, firstName) since the primary key is already an index?
回答1:
To your first question, yets, you're safe to assume that.
To the second question:
Indexes help to speed up searching - it's like an index in a book. They can help the DB engine jump to the correct record, just as an index can help you jump to the right page in a book.
The benefit to indexes that you might create youself depends on how you intend to search the data.
In your example, I'd create an INDEX on the name fields if you're going to search on them in your app.
回答2:
If there's an index on PRIMARY_KEY
, and an index on LastName, FirstName
, that does not automatically mean an index on PRIMARY_KEY, LastName, FirstName
.
However, in cases like this the primary key field is often redundant as you have a different index to work with.
来源:https://stackoverflow.com/questions/7485578/is-there-any-benefit-to-creating-and-index-on-a-primary-key