慢的SQL IN查询

时间:2018-07-04 18:15:19

标签: mysql sql

我有以下查询。我需要一个表中的信息,但是没有将这两个表链接在一起的键,并且实际上没有一种方法可以从任何一个表中引用另一个表。

我的查询

SELECT COUNT(*) 
FROM courses as c 
WHERE c.StartYear = 2016 
AND  c.student_id IN (SELECT DISTINCT p.student_id 
                      FROM programs AS p 
                      WHERE p.StartYear = 2016 
                      AND p.program_code NOT LIKE "M%")

此查询大约需要5秒钟执行时间,太长了。有更好的方法吗?

服务器:MySQL 服务器版本:5.6.35

3 个答案:

答案 0 :(得分:0)

尝试存在

SELECT COUNT(*) 
  FROM courses as c 
 WHERE c.StartYear = 2016 
   and exists (SELECT 1
                 FROM programs AS p 
                WHERE p.StartYear = 2016 
                  AND p.program_code NOT LIKE "M%" 
                  and c.student_id = p.student_id)

答案 1 :(得分:0)

exists应该比In子句更好,因此您可以尝试此查询。 Click here进行相关讨论。

SELECT COUNT(*) 
FROM courses as c 
WHERE c.StartYear = 2016 
AND Exists (SELECT 1
            FROM programs AS p 
            WHERE p.StartYear = 2016 
            AND student_id = c.student_id
            AND p.program_code NOT LIKE "M%")

答案 2 :(得分:0)

这应该给出完全相同的结果,并且可能会更快,也可能不会更快,但是确实证明了您的查询 确实 暗示这两个表可以关联由student_id

如果以下查询在逻辑上不正确,则示例查询也是如此,并且您应该提供一个虚拟示例来演示所需的逻辑:https://stackoverflow.com/help/mcve

SELECT
  COUNT(*)
FROM
  courses    c
INNER JOIN
(
  SELECT
    student_id,
    startYear
  FROM
    programs
  WHERE
    program_code NOT LIKE "M%"
  GROUP BY
    student_id,
    startYear
)
  p
    ON  p.student_id = c.student_id
    AND p.startYear  = c.startYear
WHERE
  c.StartYear = 2016