我有一个包含6条记录的测试表(table1)。我想基于列(col1)获取多个值的数据。 所以我索引了专栏。现在,如果我在IN子句中传递多个值,选择带有强制索引的所有列(*),我将获得特定记录而不是全表扫描。如果我使用选定的列运行相同的查询,我会看到它执行全表扫描。
我已经读过在select查询中使用select all(*)并不好。但是如果我不使用全选(*),那么将进行全表扫描。 我无法理解mysql如何读取查询。请帮我解决这个问题。
表格
+----+--------+---------+
| id | col1 | col2 |
+----+--------+---------+
| 1 | 100000 | E100000 |
| 2 | 100001 | E200001 |
| 3 | 100002 | E300002 |
| 4 | 100003 | E400003 |
| 5 | 100004 | E500004 |
| 6 | 100005 | E600005 |
+----+--------+---------+
INDEX
+----------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+----------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| table1 | 0 | PRIMARY | 1 | id | A | 6 | NULL | NULL | | BTREE | | |
| table1 | 1 | col1 | 1 | col1 | A | 6 | NULL | NULL | | BTREE | | |
+----------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
EXPLAIN(使用FORCE INDEX(col1)并选择所有(*)列)
select * from table1 force index(col1) where col1 in ('100000', '100001');
+----+-------------+----------+-------+---------------+-------+---------+------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+----------+-------+---------------+-------+---------+------+------+-------------+
| 1 | SIMPLE | table1 | range | col1 | col1 | 10 | NULL | 2 | Using where |
+----+-------------+----------+-------+---------------+-------+---------+------+------+-------------+
EXPLAIN(使用FORCE INDEX(col1)并且只选择1列数据而不是全部(*))
select col1 from table1 force index(col1) where col1 in ('100000', '100001');
+----+-------------+----------+-------+---------------+-------+---------+------+------+--------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+----------+-------+---------------+-------+---------+------+------+--------------------------+
| 1 | SIMPLE | table1 | range | col1 | col1 | 10 | NULL | 6 | Using where; Using index |
+----+-------------+----------+-------+---------------+-------+---------+------+------+--------------------------+
答案 0 :(得分:2)
优化器如何确定哪些更有效? 它试图预测磁盘读块操作的数量。
正如之前在评论中提到的那样,在大表上,EXPLAIN会有所不同。