条件放在WHERE
子句中的顺序根本不重要。重要的是你在桌子上的索引。
对于此查询:
SELECT *
FROM table
WHERE random_field = 4684
AND primary_field = 355
AND date <= '2012-08-01' ;
好的索引要么是要么(random_field, primary_field, date)
:(primary_field, random_field, date)
。
Why? Because the columns (random_field
, primary_field
) that have an equality conditions are placed first in the index and then the column (date
) with the range condition.
The name primary_field
is rather strange. If this is indeed the PRIMARY KEY
of the table (or if it has a UNIQUE
constraint - and thus a unique index), this is all you need to have for this query. This (primary or unique) index is as selective as the above indexes I advised. The condition will be matched by at most one row, because of the primary_field = @constant
, so there is no need for the extra indexes.