【问题标题】:I need to optimize this MYSQL query我需要优化这个 MYSQL 查询
【发布时间】:2021-02-01 23:48:04
【问题描述】:
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是有效条目,表有大量数据,需要减少执行时间。

【问题讨论】:

  • 索引呢?
  • 您可以在问题中添加 DESCRIBE 吗?
  • 请编辑问题并添加show create table student_details 和show create table subscription 和explain SELECT COUNT(...rest of your original query 的输出(不是describe,它没有足够的帮助。)

标签: mysql sql count subquery mysql-workbench


【解决方案1】:

您可以尝试使用 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 字段上有索引。由于你是按状态字段过滤的,所以对该字段的索引可以提高查询性能

【讨论】:

  • 感谢大家的投入。索引完成了这项工作。
【解决方案2】:

如果您想要与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 不是nullable。

此查询将利用subscription(student_id, status) 上的索引。

【讨论】:

  • 感谢您的输入,但处理时间较长,我需要优化查询以减少时间。
  • @SenthilKumar:你有推荐的索引吗?
  • 感谢您的投入。索引完成了这项工作
猜你喜欢
  • 1970-01-01
  • 2011-04-25
  • 2016-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-20
  • 1970-01-01
相关资源
最近更新 更多