This is my table:
- user_id INT (foreign key on `user` with the reference `id`)
- question_id INT (foreign key on `question` with the reference `id`)
- option_id INT (foreign key on `option` with the reference `id`)
- exam_id INT (foreign key on `exam` with the reference `id`)
- order INT
My Index is: user_id, exam_id
My Query:
select * from `user_answer` where `user_id` = '48' and `exam_id` = '1' and `order` > '10' order by `order` desc limit 1;
I think it should use my index but this is the result of EXPLAIN:
# id, select_type, table, type, possible_keys, key, key_len, ref, rows, Extra
'1', 'SIMPLE', 'user_answer', 'range', 'user_answer_exam_id_foreign,user_answer_user_id_exam_id_index', 'user_answer_exam_id_foreign', '4', NULL, '10', 'Using where; Using filesort'
Apperently, It is not using my index. When I use FORCE INDEX:
select * from `user_answer` force index (user_answer_user_id_exam_id_index) where `user_id` = '48' and `exam_id` = '1' and `order` > '10' order by `order` desc limit 1;
# id, select_type, table, type, possible_keys, key, key_len, ref, rows, Extra
'1', 'SIMPLE', 'user_answer', 'ref', 'user_answer_user_id_exam_id_index', 'user_answer_user_id_exam_id_index', '8', 'const,const', '10', 'Using where; Using filesort'
Any idea what's wrong with me or MySQL ?
ordera unique value in the table? At present the combination oforder > 10 ORDER BY order DESC LIMIT 1means that the optimiser believes that sorting byorderfirst will be more beneficial than filtering byuser_id, exam_id.EXPLAINresult is same.(user_id,exam_id,order)and have the query follow where condition from left to right as you have now.