简体   繁体   中英

How can I make this query run faster

I am running this query on my website in order to find a ToDo list based on specific criteria. But it runs too slow and it is probably possible to write it in another way.

SELECT * FROM lesson WHERE 
id IN 
(SELECT `lesson_id` FROM `localization_logging` 
WHERE `language_id` = 2 AND `action_id` = 1) 
AND `id` NOT IN 
(SELECT `lesson_id` FROM `localization_logging` 
WHERE `language_id` = 2 AND `part_id` = 1 AND `action_id` = 6)

What the query does is that it looks in the lesson table to find all lesson list names and then checks if a specific task is done. If the task is done in one todo than show it in the next. Action 1 is done but not action 6 in this case.

I hope I'm explaining this good enough. On my local machine the query takes 1.8 seconds, and sometimes I have to print multiple lists next to each others and then it takes 1.8 times the lists which makes the page load super slow.

Something like this for mark id as completed:

SELECT l.*, SUM(ll.action_id=6) completed FROM lesson l
INNER JOIN localization_logging ll ON ll.lesson_id = l.id
WHERE ll.language_id = 2 AND 
(
 ll.action_id = 1
  OR 
 ll.action_id = 6 AND ll.part_id == 1
)
GROUP BY l.id

And now we can wrap it with:

SELECT t.* FROM (...) t WHERE t.completed = 0

You'll usually get faster queries filtering rows with INNER/LEFT JOIN , but you need to test it.

SELECT lesson.* FROM lesson
INNER JOIN localization_logging task1
    ON lesson.id = task1.lesson_id
LEFT JOIN localization_logging task2
    ON lesson.id = task2.lesson_id
    AND task2.language_id = 2
    AND task2.part_id = 1
    AND task2.action_id = 6
WHERE task1.language_id = 2
AND task1.action_id = 1
AND task2.lesson_id IS NULL

Second table is joined on multiple conditions, but have to list them within ON clause because only results that were in result "force joined" as nulls (left join means left side stays no matter what) are required.

Btw. You'll get multiple rows from lesson if task1 condition is not limiting results to one row - GROUP BY lesson.id then.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM