MySQL 用 EXISTS 替换 IN,编辑查询要贵得多

Posted

技术标签:

【中文标题】MySQL 用 EXISTS 替换 IN,编辑查询要贵得多【英文标题】:MySQL replace IN with EXISTS, edited query is much more expensive 【发布时间】:2017-04-16 10:14:09 【问题描述】:

我有这个问题:

SELECT points.subject_id, SUM(points_in_round) 
AS points_in_round 
FROM points, subjects 
WHERE subjects.subject_id = points.subject_id 
AND subjects.subject_kind_id = 'businessman' 
AND points.subject_id IN
(SELECT subject_id FROM residents 
WHERE economic_id = 'USA' AND round_number = 1)
GROUP BY points.subject_id 
ORDER BY points_in_round DESC

我想用 EXIST 替换 IN 分句。 我重写了这样的查询:

SELECT points.subject_id, SUM(points_in_round) 
AS points_in_round 
FROM points, subjects 
WHERE subjects.subject_id = points.subject_id 
AND subjects.subject_kind_id = 'businessman' 
AND EXISTS
(SELECT * FROM residents 
WHERE economic_id = 'USA' AND round_number = 1
AND points.subject_id = residents.subject_id)
GROUP BY points.subject_id 
ORDER BY points_in_round DESC

我得到了相同的结果,但是执行计划说编辑查询的查询成本是 3100,而原始查询的查询成本是 290。

我哪里错了?

谢谢大家

【问题讨论】:

我会用 EXISTS (SELECT 1 FROM residents 替换 EXISTS (SELECT * FROM residents 但除此之外我觉得还不错 还是一样,当我这样做的时候,查询还是那么贵。 points_in_round 在哪个表中?您有歧义-points_in_round 的两种含义-一种作为列,一种作为别名。我不知道ORDER BY 对哪一个起作用。请更改该别名。 请为每个查询提供EXPLAIN SELECT...。 “查询费用”从何而来? 【参考方案1】:

我们不知道您的表上存在哪些索引。如果需要,请尝试以下查询并添加适当的索引:

SELECT points.subject_id, SUM(points_in_round) AS points_in_round 
FROM points
LEFT JOIN subjects 
  ON subjects.subject_id = points.subject_id 
LEFT JOIN residents
  ON residents.subject_id = points.subject_id
WHERE subjects.subject_kind_id = 'businessman' 
  AND economic_id = 'USA' 
  AND round_number = 1
GROUP BY points.subject_id 
ORDER BY points_in_round DESC

【讨论】:

以上是关于MySQL 用 EXISTS 替换 IN,编辑查询要贵得多的主要内容,如果未能解决你的问题,请参考以下文章

MySQL中in和exists的区别

MySql中in和exists效率

SQL优化

MySQL查询优化

MySQL - exists与in的用法

Mysql语句优化