TOP 1或EXISTS - 哪个更快?

时间:2014-04-14 13:57:19

标签: sql sql-server tsql

我在数据库中有一个表有近200万条记录。我需要找出一个客户是否有超过1条记录。我有以下两个脚本:

SELECT TOP 1 ex.exceptionId
FROM exception AS ex
WHERE ex.customerId='{1BF87745-DE00-47FF-9AC0-430BAF87679A}'
AND ex.loanId IS NULL
AND ex.statusType = 'required'
AND ex.exceptionState <> 'N'

SELECT (CASE WHEN EXISTS ( SELECT ex.exceptionId FROM exception AS ex
WHERE ex.customerId = '{1BF87745-DE00-47FF-9AC0-430BAF87679A}'
AND ex.loanId IS NULL
AND ex.statusType = 'required'
AND ex.exceptionState <> 'N') THEN 1 ELSE 0
END) AS CustomerExceptionCount

哪一个会更快,为什么......?

非常感谢..!

2 个答案:

答案 0 :(得分:1)

你不想要像

这样的东西
DECLARE @MoreThanOne Bit;

SELECT @MoreThanOne = CASE WHEN count(*) > 1 THEN 1 ELSE 0 END
FROM
(
    SELECT TOP 2 1
    FROM [exception]
    WHERE [customerId] ='{1BF87745-DE00-47FF-9AC0-430BAF87679A}'
       AND [loanId] IS NULL
       AND [statusType] = 'required'
       AND [exceptionState] <> 'N'
) [FirstTwo]

答案 1 :(得分:0)

尝试运行这些查询,您将获得查询所花费的时间

SET STATISTICS TIME ON
SELECT TOP 1 ex.exceptionId
FROM exception AS ex
WHERE ex.customerId='{1BF87745-DE00-47FF-9AC0-430BAF87679A}'
AND ex.loanId IS NULL
AND ex.statusType = 'required'
AND ex.exceptionState <> 'N'
SET STATISTICS TIME OFF
GO
SET STATISTICS TIME ON
SELECT (CASE WHEN EXISTS ( SELECT ex.exceptionId FROM exception AS ex
WHERE ex.customerId = '{1BF87745-DE00-47FF-9AC0-430BAF87679A}'
AND ex.loanId IS NULL
AND ex.statusType = 'required'
AND ex.exceptionState <> 'N') THEN 1 ELSE 0
END) AS CustomerExceptionCount
SET STATISTICS TIME OFF