简体   繁体   中英

MySql Indexing for multiple columns

My table contains columns c1,c2,c3,c4,c5,c6, I have more than 64 combination of queries like this

my queries are

  1. where (c1=1 and c2=2 and c3=3)
  2. where (c1=1 and c2=2 and c3=3 and c4 =4 and c5 =5 )
  3. where (c1=1 and c2=2 and c3=3 and c4=4)
  4. where (c1=1 and c2=2 and c3=3 and c6)
  5. where ( c2=2 and c3=3) ..etc

I created index for multiple columns using this query

create INDEX `allpair` ON TABLE_NAME (c1,c2,c3,c4,c5,c6);

but it's not working for all combinations Should I need to add indexes for all combinations?

There is no good answer.

The index you propose helps some with any query involving c1=constant , but does not help if that is missing. And, the farther you get into that multi-column index, the less useful the columns become. That is, your allpair is useless for your query 5.

A partial answer:

  • build a "few" 2- or 3-column indexes.
  • focus on columns that are likely to be tested =constant ; this is because "range" tests do not optimize as well.
  • tend to start the various indexes with different first columns
  • look at the likely queries -- you will probably find a string bias in what columns are tested. In real estate, most queries include 'number of bedrooms' but do not include 'has gazebo'.

If you had just those 5 queries, then INDEX(c2,c3,c1) (or INDEX(c3,c2,c1) ) would be perhaps best.

You cannot provide all combos. There is a hard limit of 64 indexes on a table. 5-10 is a practical limit.

Are the constants numbers? Do you need "ranges" of numbers? Are some of them strings? [If you have over-simplified the question by showing only =number , you are preventing me from providing some other solutions.]

More

  • Ranges ( > , BETWEEN , != , LIKE 'abc%' , sometimes IN , etc) -- The index won't go past that column. So, tend to put such columns at the end of a composite index.
  • 2 ranges in a WHERE -- The Optimizer will decide which one to use; usually it will pick the better one.
  • FOREIGN KEY -- This is a combination of a constraint that is used when INSERTing and INDEX that may be useful for SELECT . When adding an FK, if there is already a useful INDEX , the FK won't add a redundant index.
  • Strings ( VARCHAR , not TEXT ) -- Think of them similar to numbers when it comes to indexing.
  • DATE , DATETIME , TIMESTAMP (etc) -- These are, shall we say, glorified numbers. However, they are usually used as a "range".
  • Numbers, string, and dates all can be involved in either = or range tests. My index advice applies equally to each.

More on indexing: Index Cookbook and perhaps Entity-Attribute-Value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM