MySQL multiple indexes vs multi-column index for searching

会有一股神秘感。 提交于 2019-12-21 23:50:21

问题


In the software I'm writing one has the ability to search a given table for information. The search form has 5 fields, all which of course correspond to different columns in a table, but all of the fields are optional.

My question is in regard to whether or not multi-column indexing will work and the proper way to build a query for it.

If I have a single index across 5 columns, and I build a query to search them, when it comes to fields in this index I'm not searching, do I do something like:

field1 = 10 AND field2 > 0 AND ...

Or should I not include the unused columns at all?

I've searched around for information about multiple column indices, but I can't seem to find what to do when you need to skip one of the columns in a given index or if you simply don't care about that one in that specific instance.


回答1:


You have to understand in MySQL (in the case of InnoDB) it only uses the left most prefix of your indexes. So if the index is in Field1 + Field2, querying with only Field2 in the WHERE cannot make use of the whole index.

And if Field1 + Field2 + Field3 is the index, a query with only Field1 & Field3 in WHERE the same would happen.

Option 1

You would have to create a separate index for each search scenario if you want to optimize each search. However, if the tables are large, then the indexes would become extremely large as well. If those search queries are made very often this would be worth it.

Option 2

You can use a nifty trick if your searches have a low selectivity (i.e. Gender) by putting the low selectivity columns to the left most and use Gender IN(M, F) to include it in the WHERE clause along with the other column(s) to make use of the whole index.




回答2:


For query with criteria

field1 = 10 AND field2 > 0

you need to have composite index field1 + field2 (in this particular order)




回答3:


It depends on your queries. If you will be doing many queries with field1 and field2 often, then it makes sense to have a composite index. Otherwise you might get by fine on multiple single column indices.



来源:https://stackoverflow.com/questions/6756560/mysql-multiple-indexes-vs-multi-column-index-for-searching

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