我期望此查询使用 key 。
mysql> DESCRIBE TABLE Foo;
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | bigint(20) | NO | PRI | NULL | auto_increment |
| name | varchar(50) | NO | UNI | NULL | |
+-------+-------------+------+-----+---------+----------------+
mysql> EXPLAIN SELECT id FROM Foo WHERE name='foo';
+----+-------------+-------+------+---------------+------+---------+------+------+-----------------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+------+------+-----------------------------------------------------+
| 1 | SIMPLE | NULL | NULL | NULL | NULL | NULL | NULL | NULL | Impossible WHERE noticed after reading const tables |
+----+-------------+-------+------+---------------+------+---------+------+------+-----------------------------------------------------+
Foo 在 name
上有一个唯一索引,那么为什么在 SELECT
中不使用该索引?
最佳答案
摘自 MySQL 手册页,标题为 EXPLAIN Output Format :
Impossible WHERE noticed after reading const tables (JSON property: message)
MySQL has read all const (and system) tables and notice that the WHERE clause is always false.
以及 const 表的定义,来自标题为 Constants and Constant Tables 的页面:
A MySQL constant is something more than a mere literal in the query. It can also be the contents of a constant table, which is defined as follows:
A table with zero rows, or with only one row
A table expression that is restricted with a WHERE condition, containing expressions of the form column = constant, for all the columns of the table's primary key, or for all the columns of any of the table's unique keys (provided that the unique columns are also defined as NOT NULL).
第二个引用文献一页半长。请引用一下。
const
The table has at most one matching row, which is read at the start of the query. Because there is only one row, values from the column in this row can be regarded as constants by the rest of the optimizer. const tables are very fast because they are read only once.
const is used when you compare all parts of a PRIMARY KEY or UNIQUE index to constant values. In the following queries, tbl_name can be used as a const table:
SELECT * FROM tbl_name WHERE primary_key=1;
SELECT * FROM tbl_name WHERE primary_key_part1=1 AND primary_key_part2=2;
关于mysql - 为什么此解释中没有使用 key ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39419590/