1

是否有任何查询规则说明哪个更好首先过滤以获得最佳性能?例子:

SELECT * FROM table WHERE date <= '2012-08-01' AND random_field = 4684 AND primary_field = 355

对比

SELECT * FROM table WHERE random_field = 4684 AND primary_field = 355 AND date <= '2012-08-01'

哪个更快?where field 子句在查询中的位置会影响性能吗?我们是否应该比较

  • 初级领域优先?
  • 首先索引字段?
  • 整数字段优先?
  • 日期字段第一?
  • 字符串字段优先?
  • 子查询字段优先?

有没有你知道的流行的 mysql 查询指南?

4

2 回答 2

2

条件放在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.

于 2013-02-22T10:21:29.153 回答
0

we should follow some rules

1. comparison of primary fields should come first and then indexed (because this will filter out required value )
2. Date or range wise (example 2<id<6) should come at the end.
于 2013-02-22T10:23:53.913 回答