[英]I need to optimize this MYSQL query
SELECT COUNT(student_id) AS count
FROM student_details
WHERE STATUS='REGISTER'
AND student_id NOT IN (
SELECT student_id FROM student_details WHERE STATUS='CANCEL'
)
AND registered_on< '2020-10-15 00:00:00'
我试过 NOT EXIST 但没有得到预期的结果
SELECT COUNT(DISTINCT S.student_id) AS ren
FROM student_details S
WHERE
S.status = 'REGISTER'
AND S.registered_on < '2020-10-15 00:00:00'
AND NOT EXISTS (
SELECT 1
FROM student_details S1
WHERE S.student_id = S1.student_id AND S1.status = 'CANCEL'
)
不能做索引,因为student_id,status 的重复条目是有效条目,需要减少执行时间,因为表有大量数据。
如果您想要与第一个not exists
查询等效的内容,则逻辑是:
SELECT COUNT(*) AS ren
FROM student_details sd
WHERE
sd.status = 'REGISTER'
AND sd.registered_on < '2020-10-15 00:00:00'
AND NOT EXISTS (SELECT 1 FROM subscription s WHERE s.student_id = sd.student_id AND s.status = 'CANCEL')
那是:
子查询应该处理表subscription
,而不是student_details
。
你不想count(distinct ...)
-结局可能是一样的,如果student_id
是在一个独特的密钥student_details
,但你没有告诉。 我使用了count(*)
,它假设student_id
不能为null
。
此查询将利用subscription(student_id, status)
上的索引。
您可以尝试使用 JOIN 条件查询:
SELECT COUNT(student_details.student_id) AS count
FROM student_details
LEFT JOIN subscription
ON subscription.student_id = student_details.student_id AND subscription.status = 'CANCEL'
WHERE
student_details.status='REGISTER'
AND subscription.status IS NULL
AND registered_on< '2020-10-15 00:00:00';
这里是小提琴SQLize.online
确保您的表在 student_id 字段上有索引。 由于您按状态字段过滤,因此在该字段上建立索引可以提高查询性能
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.