[英]Why the example query with “or” do not use index?
I am reading mysql manual , 我正在阅读mysql 手册 ,
Here is a example in the manual . 这是手册中的示例。
The example create a Multiple-Column Indexes
,the index is (last_name,first_name)
该示例创建一个Multiple-Column Indexes
,索引为(last_name,first_name)
CREATE TABLE test (
id INT NOT NULL,
last_name CHAR(30) NOT NULL,
first_name CHAR(30) NOT NULL,
PRIMARY KEY (id),
INDEX name (last_name,first_name)
);
the manual said that this query will use index 手册说这个查询将使用索引
SELECT * FROM test
WHERE last_name='Widenius' AND first_name='Michael';
but the query with or
below will not use index : 但是带有or
以下的查询将不使用index:
SELECT * FROM test
WHERE last_name='Widenius' OR first_name='Michael';
why the example query with or
, namely ,why 为什么示例查询使用or
,即,为什么
SELECT * FROM test
WHERE last_name='Widenius' OR first_name='Michael';
do not use index ? 不使用索引?
Suffice it to say that databases are not good at optimizing OR
(or IN
or NOT IN
) conditions in the WHERE
clause. 可以说数据库不擅长在WHERE
子句中优化OR
(或IN
或NOT IN
)条件。
At a high level, I might describe the reason as the following. 在较高的层次上,我可能将原因描述如下。 When conditions are connecting using AND
, the first narrows the population used for the second. 当条件使用AND
连接时,第一个缩小第二个使用的总体。 This makes indexes feasible because the conditions "nest". 由于条件“嵌套”,因此使索引可行。 When using OR
, the conditions are independent. 使用OR
,条件是独立的。 I should note that some databases can handle OR
conditions better than others. 我应该注意,某些数据库可以比其他数据库更好地处理OR
条件。
If you want your code to use indexes, you can use UNION ALL
: 如果希望代码使用索引,则可以使用UNION ALL
:
SELECT t.*
FROM test t
WHERE last_name = 'Widenius'
UNION ALL
SELECT t.*
FROM test t
WHERE last_name <> 'Widenius' AND first_name = 'Michael';
For best performance, you want indexes on test(last_name)
and test(first_name, last_name)
. 为了获得最佳性能,您需要在test(last_name)
和test(first_name, last_name)
上建立索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.