在许多OR的情况下改进sql查询

时间:2014-06-12 07:33:36

标签: sql sql-server select

我有一个SQL查询,它可以有大约1.5k的ID,或者采用以下形式。它们是我拥有的人的ID,并且可以单独选择,因此每个人都被选中时会有很多OR。是选择每个人的ID更好,然后将其置于 AND 条件, UNION 而不是 OR ,或者也许使用 IN 来捆绑所有ID,因为用户可以选择每个人接受1个人。感谢。

 ...
AND (
      (UserID = '53b95690-22d8-44a2-ad56-919cb4037218')
   OR (UserID = '87b7fc0c-28f4-4f2e-9909-066df42245fa')
   OR (UserID  = '98c1b5e3-6ba5-4bd9-b8f5-d3b2221e3e3a')
   OR...

编辑:根据要求提供完整查询;

SELECT *
FROM Mail WITH (NOLOCK)
WHERE Active= 1
AND Company= '1d034e8b-0122-4531-8795-895d9287920f' 
AND (
    CompanyDivisionID= '129bcca1-b1d8-4a9e-8152-0b9e936c9d01'
    OR CompanyDivisionID= '1bf4023d-22a3-4520-b751-7842576f42b7'
    )
AND (
    (DestinationUserID = '53b95690-22d8-44a2-ad56-919cb4037218')
    OR (DestinationUserID = '87b7fc0c-28f4-4f2e-9909-066df42245fa')
    OR (DestinationUserID = '98c1b5e3-6ba5-4bd9-b8f5-d3b2221e3e3a')
            ...
            ...
            ...
    OR (DestinationUserID = '8c78fc05-7969-48fd-9b30-774e5d9a70bd')
    OR (DestinationUserID  = 'e7b76096-fe7d-44b8-9158-8293ac609471')
    OR (DestinationUserID = '8a6b7385-4339-43fb-b95b-a7b687982bcd')
    )  
ORDER BY SendingDate DESC

1 个答案:

答案 0 :(得分:2)

创建一个包含所选UserID的(临时)表并加入该表。

SELECT *
FROM Mail WITH (NOLOCK)
     inner join SelectedUsers on mail.DestinationUserID = SelectedUsers.UserID
WHERE Active= 1