【发布时间】:2015-11-19 13:23:21
【问题描述】:
我有一张大约有两三百万行的表格……
mysql> select count(*) from tbl;
+----------+
| count(*) |
+----------+
| 2615889 |
+----------+
1 row in set (1.23 sec)
mysql> show indexes from tbl;
+-------+------------+-------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------+------------+-------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| tbl | 0 | PRIMARY | 1 | tbl_id | A | 2284627 | NULL | NULL | | BTREE | | |
| ...
| tbl | 1 | tbl_fld | 1 | fld | A | 2284627 | NULL | NULL | YES | BTREE | | |
+-------+------------+-------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
6 rows in set (0.30 sec)
...对于以下查询,如果我添加 order by 子句,我似乎做得更好(即,我最终使用索引)...
mysql> explain select * from tbl
-> where fld in (select fld from tbl group by fld having count(*)>1)
-> limit 1000;
+----+--------------------+-------+-------+---------------+---------+---------+------+---------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+--------------------+-------+-------+---------------+---------+---------+------+---------+-------------+
| 1 | PRIMARY | tbl | ALL | NULL | NULL | NULL | NULL | 2328333 | Using where |
| 2 | DEPENDENT SUBQUERY | tbl | index | NULL | tbl_fld | 15 | NULL | 1 | Using index |
+----+--------------------+-------+-------+---------------+---------+---------+------+---------+-------------+
2 rows in set (0.00 sec)
mysql> explain select * from tbl
-> where fld in (select fld from tbl group by fld having count(*)>1)
-> order by fld limit 1000;
+----+--------------------+-------+-------+---------------+---------+---------+------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+--------------------+-------+-------+---------------+---------+---------+------+------+-------------+
| 1 | PRIMARY | tbl | index | NULL | tbl_fld | 15 | NULL | 1000 | Using where |
| 2 | DEPENDENT SUBQUERY | tbl | index | NULL | tbl_fld | 15 | NULL | 1 | Using index |
+----+--------------------+-------+-------+---------------+---------+---------+------+------+-------------+
2 rows in set (0.00 sec)
……这是为什么呢?
【问题讨论】:
-
您是运行查询还是只是比较他们的计划?我认为 MySQL 不会在您的第一个查询中真正扫描整个表。 LIMIT 会使其更快。
-
@Tim3880,只是
explain。
标签: mysql sql-order-by explain mysql5 mysql-5.5