优化SELECT COUNT到EXISTS

时间:2011-02-17 16:09:06

标签: sql sql-server tsql

我有查询从表中查找某些客户。

SELECT COUNT(*)
  FROM CUSTOMER
 WHERE amount <> 0
   AND customerid = 22

customerid上有一个索引,因此DB会扫描customerid = 22的所有行。

由于通过检查计数是返回零还是大于零来处理结果,我该如何优化查询?即这样,在第一个客户行的金额&lt;&gt; 0如果所有行都是= 0,则查询返回0 else,然后返回1.

4 个答案:

答案 0 :(得分:29)

select case
         when exists (select *
                      from   customer
                      where  amount <> 0
                             and customerid = 22) then 1
         else 0
       end  as non_zero_exists

答案 1 :(得分:6)

关于customerid和金额的第一个索引

CREATE INDEX customer_idx ON customer(customerid, amount); 

然后将您的查询重写为

IF EXISTS (SELECT customerid
    FROM customer
    WHERE amount > 0 -- I am assuming here that amount cannot be a negative number.
    AND customerid = 22)
   SELECT 1
ELSE
   SELECT 0

这应该导致在customer_idx上寻找索引。否则,您需要扫描该客户的所有行(您的问题似乎意味着很多)。

答案 2 :(得分:3)

似乎足够直接

IF EXISTS ( SELECT customerid
            FROM   customer
            WHERE  amount <> 0
                  and customerid = 22))
   SELECT 1
ELSE
   SELECT 0

答案 3 :(得分:2)

EXISTS的替代

select ISNULL((select TOP 1 1
               from customer
               where amount <> 0
                 and customerid = 22),0)

我已经假设您将拥有(customerid)或更好(customerid,amount)的索引。