我有一个动态查询,运行识别成员尚未租用的CD。我正在使用NOT IN子查询,但是当我有大型成员表时,它会让它们变得很慢。有关如何优化查询的任何建议
SELECT DVDTitle AS "DVD Title"
FROM DVD
WHERE DVDId NOT IN
(SELECT DISTINCT DVDId FROM Rental WHERE MemberId = AL240);
谢谢
答案 0 :(得分:5)
使用NOT EXISTS
会有更好的性能,因为它可以“短路”而不是评估每个匹配的整个集合。至少,它会比NOT IN
或OUTER JOIN
“更糟糕”,尽管每条规则都有例外。以下是我将如何编写此查询:
SELECT DVDTitle AS [DVD Title]
FROM dbo.DVD AS d
WHERE NOT EXISTS
(
SELECT 1 FROM dbo.Rental
WHERE MemberId = 'AL240'
AND DVDId = d.DVDId
);
我猜您会通过调查执行计划并确保您的索引最适合此查询(而不会对工作负载的其他部分造成负面影响)来更好地优化性能。
另见Should I use NOT IN, OUTER APPLY, LEFT OUTER JOIN, EXCEPT, or NOT EXISTS?
答案 1 :(得分:4)
SELECT DVDTitle AS "DVD Title"
FROM DVD d
left outer join Rental r on d.DVDId = r.DVDId
WHERE r.MemberId = 'AL240'
and r.DVDId is null
确保您拥有索引:
d.DVDId
r.DVDId
r.MemberId