[英]How to decrease this mysql query execution time
這是我的 MySQL 查詢:
select en.course_instance_id, count(*)
from user u
inner join enrollment en on en.user_id = u.user_id
where en.account_id=5392
and en.course_instance_id in (5127039, 5127040)
and enrollment_state='ACTIVE'
and u.state!='DELETED'
group by en.course_instance_id;
我的user
表已經user_id
作為主鍵和enrollment
表具有(user_id, course_id)
作為主鍵。
基本上,這個查詢試圖找到在每個 course_instance 中注冊的用戶數量。
現在, course_instance_id
5127039,352438個用戶就讀和course_instance_id
5127040,1個用戶登記。
當我嘗試運行此查詢時,它會超時(花費超過 2 分鍾)。
我已經檢查了兩個表上的索引,我假設它們被正確使用。 對於enrollment
的表索引course_instance_id, course_id
被使用並且為user
表中的主索引即user_id
被使用。
附加了用於此查詢的索引的快照:
對於此查詢:
select en.course_instance_id, count(*)
from user u inner join
enrollment en
on en.user_id = u.user_id
where en.account_id = 5392 and
en.course_instance_id in (5127039, 5127040) and
en.enrollment_state = 'ACTIVE' and
u.state <> 'DELETED'
group by en.course_instance_id;
我會推薦一個關於enrollment(account_id, enrollment_state, course_instance_id, user_id)
的索引。
您可以在users(user_id, state)
上添加索引,但考慮到user_id
可能是主鍵,這並不是真正需要的。
從概念上講,我認為您的查詢會更清晰。 輸出應該相同,但 mysql 可能會對 join 子句對用戶的所有限制感到滿意。 我不確定 enrollment_state 來自哪個表。
select en.course_instance_id, count(*)
from enrollment en
inner join user u on en.user_id = u.user_id and u.state!='DELETED'
where en.account_id=5392
and en.course_instance_id in (5127039, 5127040)
and enrollment_state='ACTIVE'
group by en.course_instance_id;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.