我有这个问题:
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 clausule。 我重写了这样的查询:
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.
我哪里错了?
谢谢大家
答案 0 :(得分: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