使OR查询更加简化

时间:2011-01-11 14:42:00

标签: sql sql-server tsql

我正在尝试按customerType进行搜索,而我遇到了一个小问题:

SELECT DISTINCT CustomerID, CustomerName, City, State, Zip FROM qrySearchFields 
WHERE  CustomerID in (Select CustomerID from tblCustomerTypeLineItems Where CustomerTypeID = 241)

运行不到一秒钟,所以:

SELECT DISTINCT CustomerID, CustomerName, City, State, Zip FROM qrySearchFields 
WHERE CustomerID in (Select CustomerID from tblCustomerTypeLineItems Where CustomerTypeID = 240)

但是当我尝试使用OR同时查找两种类型时:

SELECT DISTINCT CustomerID, CustomerName, City, State, Zip FROM qrySearchFields WHERE
CustomerID in (Select CustomerID from tblCustomerTypeLineItems Where CustomerTypeID = 241) 
Or CustomerID in (Select CustomerID from tblCustomerTypeLineItems Where CustomerTypeID = 240)

大约需要40秒。

有更好的方法可以做到这一点,还是我缺少的东西? 有关更多背景信息,请参阅父问题:Displaying Query Results Horizontally

4 个答案:

答案 0 :(得分:1)

为什么不重新构建OR查询,如下所示:

SELECT DISTINCT CustomerID, CustomerName, City, State, Zip 
  FROM qrySearchFields 
 WHERE CustomerID IN (SELECT CustomerID 
                        FROM tblCustomerTypeLineItems 
                       WHERE CustomerTypeID IN (241, 240))

如果您使用的是SQL Server 2005及更高版本,则可以使用公用表表达式(CTE):

WITH cteCustomerId AS 
(
    SELECT CustomerID
      FROM tblCustomerTypeLineItems
     WHERE CustomerTypeID IN (241, 240)
)
SELECT DISTINCT CustomerID, CustomerName, City, State, Zip
  FROM qrySearchFields
 WHERE CustomerID IN (SELECT CustomerID
                        FROM cteCustomerId);

答案 1 :(得分:1)

为什么在外部查询中使用OR

试试这个:

SELECT  DISTINCT CustomerID, CustomerName, City, State, Zip
FROM    qrySearchFields
WHERE   CustomerID IN
        (
        SELECT  CustomerID
        FROM    tblCustomerTypeLineItems
        WHERE   CustomerTypeID IN (240, 241)
        )

答案 2 :(得分:1)

由于两个SELECT IN语句,它不得不做更多的工作;效率更高:

SELECT DISTINCT CustomerID, CustomerName, City, State, Zip 
FROM qrySearchFields
WHERE CustomerID in
      (Select CustomerID from tblCustomerTypeLineItems Where CustomerTypeID IN (240,241))

答案 3 :(得分:1)

2个子查询可能相当昂贵。试试这个版本:

SELECT DISTINCT sf.CustomerID, sf.CustomerName, sf.City, sf.State, sf.Zip 
    FROM qrySearchFields sf
        INNER JOIN tblCustomerTypeLineItems ctli
            ON sf.CustomerID = ctli.CustomerID
                AND ctli.CustomerTypeID IN (240,241)