(正在使用SQL Server 2012)
我找到了一些关于查询优化的主题,并将EXISTS与COUNT进行比较,但我找不到这个确切的问题.
我有一个看起来像这样的查询:
select * from
tblAccount as acc
join tblUser as user on acc.AccountId = user.AccountId
join tblAddress as addr on acc.AccountId = addr.AccountId
... **a few more joins**
where acc.AccountId in (
select * accountid from
(select accountid, count(*) from tblUser
where flag = 1
group by accountId) as tbl where c != 1
Run Code Online (Sandbox Code Playgroud)
此查询立即运行(尽管db非常大,大约70Gb).
当我将查询包装在EXISTS中时,如下所示:
if exists
(
**Exact same query as above**
)
begin
RAISERROR('Account found without exactly one flagged user.', 16, 1);
end …Run Code Online (Sandbox Code Playgroud)