简体   繁体   English

为什么我的MySQL不使用索引?

[英]Why my mysql doesn't use index?

I'm tuning my query for mysql. 我正在调整mysql查询。 the schema has index of user_id (following..) but the index is not used. 该架构具有user_id的索引(以下..),但未使用该索引。 why? 为什么?

Env: MySQL4.0.27,MyISAM 环境:MySQL4.0.27,MyISAM

SQL is the following : SQL如下:

SELECT type,SUM(value_a) A, SUM(value_b) B, SUM(value_c) C
FROM  big_record_table
WHERE  user_id='<user_id>'
GROUP BY type

Explain: 说明:

|table |type |possible_keys |key |key_len |ref |rows |Extra|

|big_record_table| ALL| user_id_key|||| 1059756 |Using where; Using temporary; Using filesort|

could you describe detail? 你能描述细节吗?

scheme is following: 方案如下:

CREATE TABLE `big_record_table` (
 `user_id` int(11) NOT NULL default '0',
 `type` enum('type_a','type_b','type_c') NOT NULL default 'type_a',
 `value_a` bigint(20) NOT NULL default '0',
 `value_b` bigint(20) default NULL,
 `value_c` bigint(20) NOT NULL default '0',
 KEY `user_id_key` (`user_id`)
) TYPE=MyISAM

My guess is that type and user_id are not indexed . 我的猜测是typeuser_id没有indexed

Just a will run. 只是将运行。 You're not giving much to play with. 您没有太多可玩的东西。

First, we don't see how your indexes are declared. 首先,我们看不到如何声明您的索引。 Can you get a dump of the tables? 你能把桌子丢掉吗? In PostgreSQL you'd use pg_dump but I don't know how in MySQL. 在PostgreSQL中,您将使用pg_dump但在MySQL中我不知道如何使用。 Have you done an ANALYZE on the table? 您在桌子上做过分析吗?

It could be that implicit type conversion is preventing your index from being used. 隐式类型转换可能会阻止您的索引被使用。 You have defined user_id as an int, but specified a string in the query. 您已将user_id定义为一个int,但在查询中指定了一个字符串。 This gives MySQL the option of either converting the string in the query into an int (which might not be accurate) - or convert every user_id in the database into a string to compare against the string in the query. 这使MySQL可以选择将查询中的字符串转换为int(可能不准确)-或将数据库中的每个user_id转换为字符串以与查询中的字符串进行比较。

Short answer: try removing the quotes in the query 简短答案:尝试删除查询中的引号

SELECT type,SUM(value_a) A, SUM(value_b) B, SUM(value_c) C
FROM  big_record_table
WHERE  user_id=123
GROUP BY type

(where 123 is replaced with the correct user-id). (其中123替换为正确的用户ID)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM