I'm trying to find exam results for individual people between multiple periods using this query:
SELECT * FROM RESULTS AS R, Define_Times AS T
WHERE R.PERSONID = T.PERSONID AND (
(R.DATE BETWEEN T.Previous_Month_Start AND T.Previous_Month_End) OR
(R.DATE BETWEEN T.Next_Month_Start AND T.Next_Month_End) OR
(R.DATE BETWEEN T.Six_Month_Start AND T.Six_Month_End) OR
(R.DATE BETWEEN T.One_Year_Start AND T.One_Year_End) OR
(R.DATE BETWEEN T.Two_Year_Start AND T.Two_Year_End) OR
(R.DATE BETWEEN T.Three_Year_Start AND T.Three_Year_End) OR
(R.DATE BETWEEN T.Four_Year_Start AND T.Four_Year_End) )
Previous/Next/One_Year etc. is different for each person.
Explain gives:
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
| 1 | SIMPLE | T | ALL | PEOPLE | NULL | NULL | NULL | 75775 | |
| 1 | SIMPLE | R | ref | IDX3,IDX2 | IDX3 | 5 | T.PERSONID | 3550 | Using where |
The Results table has about 300 million rows. Define_Times has 75,000.
It's taking AGES.
I see that the 1st type is ALL, which is bad. But if it's so bad, why is it not using the index on PERSONID (called PEOPLE) it identified as a possible? What can I do to improve this?
I also can't see it using an index for date - there's one on R.DATE. (It's the first in the sequence of 5 on the index called IDX2.)
Sorry for any typos - my keyboard is broken, and thanks in advance.