如何减少mysql查询执行时间

如何减少mysql查询执行时间,mysql,sql,query-performance,Mysql,Sql,Query Performance,这是我的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!='DELETE

这是我的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;
我的
用户
表将
用户id
作为主键,
注册
表将
(用户id,课程id)
作为主键

基本上,此查询试图查找每个course_实例中注册的用户数

现在,对于
course\u instance\u id
5127039,注册了352438个用户,对于
course\u instance\u id
5127040,注册了1个用户

当我尝试运行此查询时,它将超时(需要2分钟以上)

我已经检查了这两个表上的索引,并假设它们使用正确。对于
注册
课程实例id的表索引,使用课程id,对于
用户
表主索引,即
用户id

已附加用于此查询的索引的快照:


从概念上讲,我认为你的问题会像这样更清楚。输出应该是相同的,但是mysql可能会更高兴,因为在join子句中对用户有所有的限制。我不确定哪个州是哪个表

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;
对于此查询:

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;
选择en.course\u instance\u id,count(*)
从用户u内部联接
入学人数
在en.user\u id=u.user\u id上
其中en.account_id=5392和
(51270395127040)和
en.enrollment_state=“活动”和
u、 声明“已删除”
按en.course\u instance\u id分组;
我建议在
注册(帐户\u id、注册\u状态、课程\u实例\u id、用户\u id)上建立一个索引


您可以在
用户(用户id,状态)
上添加索引,但鉴于
用户id
可能是主键,因此实际上不需要添加索引。

执行
描述分析选择…
以查看成本结构。MySQL是一款不会体验幸福等情绪的软件(幸灾乐祸可能是另一回事)。也就是说,在
on
子句和
where
子句中过滤内部联接应该没有什么区别。经过几次测试,我得出了相同的结论。我认为选择从注册加入到用户更清晰,因为查询实际上选择的是从注册而不是用户,但这与性能改进是一个单独的问题……,至少对于
内部加入来说不是这样。(
/
可能很重要。)谢谢。该指数有助于大幅减少执行时间。