0

Below is my SQL query.

SELECT `left_table`.`right_table_id`, MAX(left_table.add_time) AS max_add_time 
    FROM `left_table` 
    LEFT JOIN `right_table` ON `left_table`.`right_table_id` = `right_table`.`id` 
    WHERE left_table.add_time <= NOW()
        AND (
                (right_table.some_id = 1 AND right_table.category != -2)
                OR
                (right_table.another_id = 1 AND right_table.category != -1)
        ) AND NOT(right_table.category = -3) 
        AND NOT(right_table.category = -4) 
    GROUP BY `right_table_id` 
    ORDER BY `max_add_time` DESC, `left_table`.`id` DESC
LIMIT 12

It takes 5356.6ms to execute this query. It takes too long to me. I have been trying and trying to speed up the execution time. But no result. How can I improve the execution time for the above query?

2
  • 1
    Can you share explain plan? Jul 11, 2017 at 14:47
  • Is left_table.add_time indexed? That would speed up the efficiency of the MAX() if it isn't.
    – Trojan404
    Jul 11, 2017 at 15:01

1 Answer 1

1

Hmmm . . . I would start by writing the logic like this:

SELECT COUNT(DISTINCT lt.`right_table_id`)
FROM `left_table` lt LEFT JOIN
     `right_table` rt
      ON lt.`right_table_id` = rt.`id` 
WHERE lt.add_time <= NOW() AND
      ((rt.some_id = 1 AND rt.category <> -2) OR
       (rt.another_id = 1 AND rt.category <> -1)
      ) AND
      rt.category NOT IN (-3, -4);

There might be additional simplifications, depending on whether lt.right_table_id always matches a row in the right table (or is NULL). And various other considerations.

1
  • Dude, thanks for your answer. How about my SELECT query without COUNT() function. How can I speed it up. Because without the COUNT() function is the execution time also long.
    – O Connor
    Jul 12, 2017 at 8:37

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.