我想知道为什么mysql在表(visit_url)上的以下查询中没有使用索引:
> describe select sv.url from visit_url sv, result_query rq where rq.result_id = sv.result_id and rq.user_id = 'fred';
+----+-------------+-------+--------+---------------+---------+---------+------------------------+--------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+--------+---------------+---------+---------+------------------------+--------+-------------+
| 1 | SIMPLE | vu | ALL | result_id | NULL | NULL | NULL | 506553 | |
| 1 | SIMPLE | rq | eq_ref | PRIMARY | PRIMARY | 32 | vu.result_id | 1 | Using index |
+----+-------------+-------+--------+---------------+---------+---------+------------------------+--------+-------------+
我的索引是:
mysql> show index in visit_url;
+-----------+------------+-----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-----------+------------+-----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| visit_url | 1 | result_id | 1 | result_id | A | 168851 | NULL | NULL | | BTREE | | |
| visit_url | 1 | url | 1 | url | A | 253276 | NULL | NULL | YES | BTREE | | |
+-----------+------------+-----------+--------------+-------------+-----------+-------------+-------- --+--------+------+------------+---------+---------------+
和
mysql> show index in result_query;
+--------------+------------+-----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+--------------+------------+-----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| result_query | 0 | PRIMARY | 1 | result_id | A | 2718272 | NULL | NULL | | BTREE | | |
| result_query | 1 | query_idx | 1 | query | A | 271827 | NULL | NULL | | BTREE | | |
+--------------+------------+-----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
visit_url有506k条目,result_query有2mil
非常感谢!
答案 0 :(得分:0)
尝试使用与where子句分开的显式连接编写查询,如下所示:
select sv.url from visit_url sv
join result_query rq on rq.result_id = sv.result_id
where rq.user_id = 'fred';
答案 1 :(得分:0)
result_query.user_id
未编入索引。因此,使用user_id
查找行将需要200万行的完整扫描。相反,它会扫描500k行visit_url
,并使用主键与result_query
联接。这样,它必须扫描最多500k行才能找到请求的user_id
。