【发布时间】:2017-12-19 09:21:35
【问题描述】:
我有一张下表:
CREATE TABLE `student` (
`name` varchar(30) NOT NULL DEFAULT '',
`city` varchar(30) NOT NULL DEFAULT '',
`age` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`name`,`city`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
我想知道,如果我执行以下两条SQL,它们的性能是否相同?
mysql> select * from student where name='John' and city='NewYork';
mysql> select * from student where city='NewYork' and name='John';
涉及的问题:
- 如果有一个多列索引(name、city),两个sql都用吗?
- 优化器会不会因为索引把第二条sql改成第一条?
我对他们两个执行解释,结果如下:
mysql> explain select * from student where name='John' and city='NewYork';
+----+-------------+---------+-------+---------------+---------+---------+-------------+------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+---------+-------+---------------+---------+---------+-------------+------+-------+
| 1 | SIMPLE | student | const | PRIMARY | PRIMARY | 184 | const,const | 1 | NULL |
+----+-------------+---------+-------+---------------+---------+---------+-------------+------+-------+
mysql> 解释 select * from student where city='NewYork' and name='John';
+----+-------------+---------+-------+---------------+---------+---------+-------------+------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+---------+-------+---------------+---------+---------+-------------+------+-------+
| 1 | SIMPLE | student | const | PRIMARY | PRIMARY | 184 | const,const | 1 | NULL |
+----+-------------+---------+-------+---------------+---------+---------+-------------+------+-------+
【问题讨论】:
-
多列索引中的列顺序很重要。可以使用列
name和city上的索引来代替列name上的索引,但不能使用它来代替列city上的索引。WHERE子句中的条件顺序无关紧要。 -
欢迎来到 Stack Overflow。你问的第一个问题做得很好。
标签: mysql sql indexing query-performance