为什么select where查询行为与where where where条件不同而没有单引号

时间:2017-05-25 14:16:00

标签: mysql sql plsql plsqldeveloper

我在使用单引号和没有单引号执行查询时观察到了不同的行为。

使用单引号('121')我快速得到了结果,查询正在使用索引。但是没有单引号,查询不使用索引,响应时间很长。

mysql> explain  select * from tbl_n1 where id =121;
+----+-------------+----------------------+------+---------------+------+---------+------+--------+-------------+
| id | select_type | table                | type | possible_keys | key  | key_len | ref  | rows   | Extra       |
+----+-------------+----------------------+------+---------------+------+---------+------+--------+-------------+
|  1 | SIMPLE      | tbl_n1               | ALL  | n1_id      | NULL | NULL    | NULL | 286929 | Using where |
+----+-------------+----------------------+------+---------------+------+---------+------+--------+-------------+
1 row in set (0.00 sec)

mysql> explain  select * from tbl_n1 where id ='121';
+----+-------------+----------------------+------+---------------+----------+---------+-------+------+-------------+
| id | select_type | table                | type | possible_keys | key      | key_len | ref   | rows | Extra       |
+----+-------------+----------------------+------+---------------+----------+---------+-------+------+-------------+
|  1 | SIMPLE      | tbl_n1               | ref  | n1_id       | n1_id  | 53      | const |   29 | Using where |
+----+-------------+----------------------+------+---------------+----------+---------+-------+------+-------------+
1 row in set (0.00 sec)


show create table tbl_n1\G
....
....
 `id` varchar(10)  DEFAULT NULL,
....
....
....

1 个答案:

答案 0 :(得分:5)

由于字段id的定义为varchar,如果没有单引号,数据库必须对字段id进行隐式转换强制转换(或将其转换为varchar的任何函数),这将阻止使用索引idx_1055

阅读这篇文章:Type Conversion in Expression Evaluation