I have a table with at least a couple of million rows and a diagram of all integers that looks something like this:
start stop first_user_id second_user_id
Strings are pulled using the following queries:
SELECT * FROM tbl_name WHERE stop >= M AND first_user_id=N AND second_user_id=N ORDER BY start ASC SELECT * FROM tbl_name WHERE stop >= M AND first_user_id=N ORDER BY start ASC
I canβt determine the best indexes to speed up these queries. The problem is that ORDER BY, because when I accept this, queries are fast.
I tried all different types of indexes using the standard index format:
ALTER TABLE tbl_name ADD INDEX index_name (index_col_1,index_col_2,...)
And none of them seem to speed up query execution. Does anyone know which index will work? Also, should I try to use a different type of index? I cannot guarantee the uniqueness of each row, so I avoided UNIQUE indexes.
Any guidance / help would be appreciated. Thanks!
Update: here is a list of indexes, I did not include this initially, since I took a shotgun approach and added a ton of indexes that are looking for the one that works:
start_index: [start, first_user_id, second_user_id] stop_index: [stop, first_user_id, second_user_id] F1_index: [first_user_id] F2_index: [second_user_id] F3_index: [another_id] test_1_index: [first_user_id,stop,start] test_2_index: [first_user_id,start,stop] test_3_index: [start,stop,first_user_id,second_user_id] test_4_index: [stop,first_user_id,second_user_id,start] test_5_index: [stop,start]
And here is the output of EXPLAIN.
*************************** 1. row *************************** id: 1 select_type: SIMPLE table: listing type: index_merge possible_keys: stop_index,F1_index,F3_index,test_1_index,test_2_index,test_4_index,test_5_index key: F1_index,F3_index key_len: 5,5 ref: NULL rows: 238 Extra: Using intersect(F1_index,F3_index); Using where; Using filesort
Update for posterity
We completed a complete re-evaluation of how we requested the table, and selected these indexes:
index_select_1: [first_user_id,start,stop] index_select_2: [first_user_id,second_user_id,start,stop]
and then we select in the table such queries as:
SELECT * FROM tbl_name WHERE first_user_id=N AND start >= M ORDER BY start ASC SELECT * FROM tbl_name WHERE first_user_id=N AND second_user_id=N AND start >= M ORDER BY start ASC
Thanks to everyone who answered, you really helped me solve this problem.