Which column to put first in index? Higher or lower cardinality?

删除回忆录丶 提交于 2019-12-31 02:51:09

问题


For example, if I have a table with a city and a state column, what is the best way to use the index?

Obviously city will have the highest cardinality, so should I put that column first in the index, should I put state or doesn't it matter much?


回答1:


MySQL composite index lookups must take place in the order in which the columns are defined within the index. Since you want MySQL to be able to discriminate between records by performing as few comparisons as possible, with all other things being equal you will benefit most from from a composite index in which the columns are ordered from highest- to lowest-cardinality.

That is, assuming comparisons must eventually be performed against the highest cardinality column in order to discriminate records, why force comparisons to take place first against the lowest cardinality column when ultimately that may be unnecessary?




回答2:


It does not matter in this case:

INDEX cs (city, state),
INDEX sc (state, city)

WHERE city = 'Atlanta'
  AND state = 'Georgia'

With either index, the drill-down in the BTree will be the same effort, and you will get to the one row just as fast.

(The order of clauses in WHERE does not matter.)

(If you are using a "range" test instead of = test, well, that's a different Question.)



来源:https://stackoverflow.com/questions/12315496/which-column-to-put-first-in-index-higher-or-lower-cardinality

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!