插入n多的数据后来做测试,首先查看插入的数据记录数。
SELECT count(*) FROM users;
+----------+
| count(*) |
+----------+
| 5925 |
+----------+
1 row in set (1.85 sec)
我们写两个SQL,一个
SELECT SQL_NO_CACHE count(*) FROM users WHERE stat = 0;
+----------+
| count(*) |
+----------+
| 3640 |
+----------+
1 row in set (0.05 sec)
再看另一个SELECT SQL_NO_CACHE count(*) FROM users WHERE stat = '0';
+----------+
| count(*) |
+----------+
| 3566 |
+----------+
1 row in set (0.00 sec)
为什么前面一种写法执行所需要时间较长并且所选择出的记录数多一些呢?
我们使用EXPLAIN看一下对索引的使用情况。
EXPLAIN SELECT SQL_NO_CACHE count(*) FROM users WHERE stat = 0;
+----+-------------+-----------+-------+---------------+-----------+---------+------+------+--------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-----------+-------+---------------+-----------+---------+------+------+--------------------------+
| 1 | SIMPLE | users | index | phonestat | phonestat | 75 | NULL | 5925 | Using where; Using index |
+----+-------------+-----------+-------+---------------+-----------+---------+------+------+--------------------------+
1 row in set (0.00 sec)
看rows 5925,实际进行了一次全表检索,索引没有用上。
再看第二种
EXPLAIN SELECT SQL_NO_CACHE count(*) FROM users WHERE stat = '0';
+----+-------------+-----------+------+---------------+-----------+---------+-------+------+--------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-----------+------+---------------+-----------+---------+-------+------+--------------------------+
| 1 | SIMPLE | users | ref | phonestat | phonestat | 12 | const | 2968 | Using where; Using index |
+----+-------------+-----------+------+---------------+-----------+---------+-------+------+--------------------------+
1 row in set (0.00 sec)