I have a single table where I need to query based on 4 columns a,b,c,d The most common query will be a select based on all 4 columns at the same time, however I need to be able to search quickly for each of the columns taken separately, or also combinations of them (e.g. a&b, a&d, b&c&d and so on). Shall I create an index for every combination? or it's better to have only an index for a&b&c&d and one for a, one for b, one for c, one for d? in this last case a query that matches only a&b for example will be sped up because both a and be have an index?
相关问题
- how to get selected text from iframe with javascri
- Faster loop: foreach vs some (performance of jsper
- sqlyog export query result as csv
- NOT DISTINCT query in mySQL
- Why wrapping a function into a lambda potentially
If you want to satisfy all the combinations with an index, you need the following:
You don't need other combinations because any prefix of an index is also an index. The first index will be used for queries that test just
a
,a&b
,a&b&c
, so you don't need indexes for those combinations.Whether you really need all these indexes depends on how much data you have. It's possible that just having indexes on each column will narrow down the search sufficiently that you don't need indexes on the combinations. The only real way to tell is by benchmarking the performance of your applications. The indexes take up disk space and memory, so trying to create all possible indexes can cause problems of its own; you need to determine if the need is strong enough.
One thing to note is that a "range" is only useful as the last item in an index:
Another thing: "flags" (true/false, etc) are useless to index by themselves. They can be somewhat useful in combination:
Also, order matters in the
INDEX
, but not in theWHERE
: Suppose you haveINDEX(a,b)
:If some column is always a range (such as a date), it gets messier. For optimal indexing two indexes are needed here:
So, I might do these:
More on understanding index creation.