0

I need to optimize a MySQL query. I have a table 'betting' with less than 100.000 records. I need to display all records for the current month.

SELECT betting.id 
FROM betting, members 
WHERE members.status = 1 
and members.id = betting.user 
and betting.date between '2016-09-01' and '2016-09-30' 
and betting.status = 1 
and betting.type = 1;

When i try the explain command:

SIMPLE  betting range   user,date,type,type_2   type_2  7   NULL    4966    Using where
SIMPLE  members eq_ref  PRIMARY PRIMARY 4   betting.user    1   Using where

Is there any chance to reduce the database searches ? The problem is that the page which displays this results is called too often and that causes a lot of CPU costs. Unfortunately i cannot cache the results, because they need to be live. Any ideas ?

4
  • Do you have indexes on any relevant columns Commented Sep 19, 2016 at 12:07
  • You can use cache dependency with mysql. It means that you will keep your results in cache until the table changes. Commented Sep 19, 2016 at 12:32
  • @RiggsFolly yes, I have an index on (type, result, status) Commented Sep 19, 2016 at 20:45
  • @OffirPe'er how can i use these cache dependencies ? Commented Sep 19, 2016 at 20:46

1 Answer 1

1

Here is your query written in a format that is easier (at least for me) to understand:

SELECT b.id 
FROM betting b join
     members m
     ON m.id = b.user 
WHERE m.status = 1  
      b.date between '2016-09-01' and '2016-09-30' and
      b.status = 1 and
      b.type = 1;

I think the best indexing strategy is: betting(status, type, date, user) and members(id, status).

Sign up to request clarification or add additional context in comments.

4 Comments

I agree with you about the readability, but this query does not help me. Is still needs to search in around 5000 rows. I am not sure if my query can be optimized more ...
@VinceCarter . . . Did you add the indexes?
yes, now the situation hasn't changed a lot: 1 SIMPLE b range user,date,type,type_2 type_2 5 NULL 4759 Using index condition 1 SIMPLE m eq_ref PRIMARY,id PRIMARY 4 b.user 1 Using where
@VinceCarter Does the number of rows matter if it is fast? What is the execution time of your query now? What was the execution time of your original query, before the indexes? Make sure to run each at least twice, and discard the first result of each, else the buffer cache will distort the results.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.