SQL这些是一样的吗?

时间:2011-02-15 18:59:53

标签: sql sql-server sql-server-2005

这些是一样的吗?

INNER JOIN dbo.ReportingLevels rl ON e.ei_CompanyID = rl.rl_CompanyId
    AND e.ei_Level = rl.rl_index
    AND EXISTS (SELECT * FROM @ReportingLevelId rlid
                WHERE rlid.[reportLevelName] = rl.[rl_name])    
    AND EXISTS (SELECT * FROM @ReportingLevelId rlid
                WHERE rlid.[companyid] = rl.[rl_CompanyId])

这是第二个。

INNER JOIN dbo.ReportingLevels rl ON e.ei_CompanyID = rl.rl_CompanyId
    AND e.ei_Level = rl.rl_index
    AND EXISTS (SELECT * FROM @ReportingLevelId rlid
                WHERE rlid.[reportLevelName] = rl.[rl_name]
                  AND rlid.[companyid] = rl.[rl_CompanyId]))    

我认为这些是相同的,但是当我使用类似的变体时,我得到了一个奇怪的结果。

2 个答案:

答案 0 :(得分:8)

不,他们不是。如果表@ReportingLevelId中存在rl_name和rl_CompanyId,则第一个将选择一行,但不一定在同一行中。第二个要求这些值出现在同一行中。

答案 1 :(得分:0)

您的secound sql存在问题,您使用的是AND而不是OR。您可以看到上面的正确答案。

INNER JOIN dbo.ReportingLevels rl ON e.ei_CompanyID = rl.rl_CompanyId AND e.ei_Level = rl.rl_index
AND EXISTS (SELECT * FROM @ReportingLevelId rlid WHERE rlid.[reportLevelName] = rl.[rl_name] OR rlid.[companyid] = rl.[rl_CompanyId]))