I have an app in production right now that makes a MySQL query to select columns in a table that do not have an associated row in another table To do so, I am currently using a MySQL exists query that appears to becoming slower and slower the more results that are added.
This is an example of the current query:
SELECT m.ig_media_id, m.media_promotion_id FROM media_promotions m
WHERE m.likes_received < m.likes_requested
AND m.user_id != 19
AND m.active = 1
AND NOT EXISTS
(SELECT * from media_actions m_a WHERE m_a.user_id = 19 AND m_a.ig_media_id = m.ig_media_id)
ORDER BY m.created_at ASC
LIMIT 1
What can I do to speed this up? It is currently running at ~3 seconds and really slowing down my application.
This is the subquery:
NOT EXISTS (SELECT *
from media_actions m_a
WHERE m.user_id = 19 AND m_a.ig_media_id = m.ig_media_id
)
You can speed this up with an index:
create index idx_media_actions on media_actions(ig_media_id, user_id)
You can also phrase this as:
NOT EXISTS (SELECT 1
from media_actions m_a
WHERE m.user_id = 19 AND m_a.ig_media_id = m.ig_media_id
)
However, I think MySQL is smart enough to ignore the *
in such a subquery.
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.