tags:

views:

43

answers:

3

I'm tuning my query for mysql. the schema has index of user_id (following..) but the index is not used. why?

Env: MySQL4.0.27,MyISAM

SQL is the following :

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
A: 

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. Have you done an ANALYZE on the table?

Andy Lester
Thank you . yes I've ANALYZEd
ffffff
OK, but what about the table layouts. I don't see how your indexes are defined. Did you create an index on big_record_table? How exactly was that index created?
Andy Lester
I've wrote the scheme . could you give me why? Should I read source code of mysql optimizer?
ffffff
+1  A: 

My guess is that type and user_id are not indexed.

Just a will run. You're not giving much to play with.

Frankie
Thank you for replying . but I wanna get Why only user_id is not OK?
ffffff
@ffffff you're grouping by `type`. If you get a huge bunch of results with the `user_id` they will all have to be read to find out about different types.
Frankie
Thank you so much! If you know a documents listed in . I'm happy
ffffff
A: 

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. 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.

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).

Martin