SQL查询应该做同样的事情,但不要

时间:2015-10-13 14:36:26

标签: sql sql-server tsql

下面的两个SQL查询应该给我完全相同的结果,但由于某种原因,第一个使用连接而不是子查询的查询给了我更多的结果。唯一的区别是两个样本中的最后一行。谁能告诉我为什么?

SELECT *
FROM TravelReport TR
  JOIN School SC ON SC.SchoolId = TR.SchoolId 
  LEFT OUTER JOIN [User] U ON U.UserId = TR.UserId
                          AND U.UserTypeId = 3 
                          AND U.UserStatusId = 1 
  JOIN ProjectSchools PS ON PS.SchoolId = SC.SchoolId
WHERE PS.Active = 1
  AND PS.ProjectId = 2

=====

SELECT *
FROM TravelReport TR
  JOIN School SC ON SC.SchoolId = TR.SchoolId 
  LEFT OUTER JOIN [User] U ON U.UserId = TR.UserId
                          AND U.UserTypeId = 3 
                          AND U.UserStatusId = 1 
WHERE SC.SchoolId in (SELECT DISTINCT PS.SchoolId FROM ProjectSchools PS
                      WHERE PS.Active = 1 AND PS.ProjectId = 2)

1 个答案:

答案 0 :(得分:0)

可以消除左边因为它不应该影响任何计数 你确定你不只是得到更多相同的结果吗?

SELECT *
  FROM TravelReport TR      
  JOIN School SC 
        ON SC.SchoolId = TR.SchoolId  
  JOIN ProjectSchools PS 
        ON PS.SchoolId = SC.SchoolId 
 WHERE PS.Active    = 1
   AND PS.ProjectId = 2
=====

SELECT *
  FROM TravelReport TR
  JOIN School SC 
        ON SC.SchoolId = TR.SchoolId  
 WHERE SC.SchoolId in ( SELECT DISTINCT PS.SchoolId 
                          FROM ProjectSchools PS
                         WHERE PS.Active    = 1 
                           AND PS.ProjectId = 2 )

考虑一下

SchoolID  Active  ProjectID 
10        1       2
10        1       2 
10        1       1
11        2       2
12        1       2
13        1       2
13        2       2

第一个将为schoolID 10返回两行,第二个不会

也许学校可以拥有多个活跃的项目,因此您无法使SchoolID独一无二 至少在SchoolID,Active,ProjedtID

上设置了一个独特的约束

或者只是在select *
中加上一个明显的 选择不同的*

如果还有其他事情发生,请发布实际数据以重现问题