我在使用单引号和没有单引号执行查询时观察到了不同的行为。
使用单引号('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,
....
....
....
答案 0 :(得分:5)
由于字段id
的定义为varchar
,如果没有单引号,数据库必须对字段id
进行隐式转换强制转换(或将其转换为varchar的任何函数),这将阻止使用索引idx_1055