此查询中的IN语句是多余的吗?

时间:2013-01-18 07:12:50

标签: sql tsql sql-server-2005

我收到了像这样的查询

SELECT * FROM dayTable
LEFT JOIN ProcessTable firstprocess
ON dayTable.id = a.daytablefkid 
AND firstprocess.processid in (1234)
AND firstprocess.daytablefkid 
     IN (SELECT id 
         FROM daytable  
         WHERE dayTable.DateFrom > @dateFrom 
         AND dayTable.DateTo < @dateTo)

LEFT JOIN ProcessTable secondprocess
ON daytable.id = secondprocess.daytablefkid
and secondprocess.processid in (4567)
    IN (SELECT id 
        FROM daytable 
        WHERE dayTable.DateFrom > @dateFrom 
        AND dayTable.DateTo < @dateTo)


WHERE dayTable.DateFrom > @dateFrom AND dayTable.DateTo < @dateTo

首先我注意到,连接中的第一个IN语句“IN(XXXX)”可以转换为WHERE语句,但两个连接中的第二个IN语句有点令人困惑,因为相同的过滤是也在查询结束时完成。

我想知道它们是否确实是多余的,或者如果删除它们会导致结果集不同吗?

2 个答案:

答案 0 :(得分:0)

是的,IN (SELECT id FROM daytable WHERE dayTable.DateFrom > @dateFrom AND dayTable.DateTo < @dateTo) - 部分是多余的,因为您已经加入了日历表,您有相同的WHERE条款。

此查询应该给出相同的结果:

SELECT * 
FROM dayTable
LEFT JOIN ProcessTable firstprocess
  ON dayTable.id = firstprocess.daytablefkid 
    AND firstprocess.processid = 1234
LEFT JOIN ProcessTable secondprocess
  ON daytable.id = secondprocess.daytablefkid
    AND secondprocess.processid = 4567
WHERE 
  dayTable.DateFrom > @dateFrom 
  AND dayTable.DateTo < @dateTo

答案 1 :(得分:0)

请求的另一个选项优化

SELECT * 
FROM dayTable 
  LEFT JOIN ProcessTable process ON dayTable.id = process.daytablefkid 
    AND process.processid IN (1234, 4567)
WHERE dayTable.DateFrom > @dateFrom AND dayTable.DateTo < @dateTo