在我的項目中,我使用實體框架4.4.0.0,我有以下困境。我必須檢查用戶是否被激活。我的查詢是這樣的:在實體框架中比較Any()和Count Count()生成的查詢的性能5
任何()
_context.Users.Any(u => u.Id == userId && u.IsActivated);
生成的SQL是:
SELECT CASE
WHEN (EXISTS (SELECT 1 AS [C1]
FROM [dbo].[Users] AS [Extent1]
WHERE ([Extent1].[Id] = @p__linq__0)
AND ([Extent1].[IsActivated] = 1))) THEN cast(1 AS BIT)
WHEN (NOT EXISTS (SELECT 1 AS [C1]
FROM [dbo].[Users] AS [Extent2]
WHERE ([Extent2].[Id] = @p__linq__0)
AND ([Extent2].[IsActivated] = 1))) THEN cast(0 AS BIT)
END AS [C1]
FROM (SELECT 1 AS X) AS [SingleRowTable1]
對於Count()
我這樣的語句:
SELECT [GroupBy1].[A1] AS [C1]
FROM (SELECT COUNT(1) AS [A1]
FROM [dbo].[Users] AS [Extent1]
WHERE ([Extent1].[Id] = @p__linq__0)
AND ([Extent1].[IsActivated] = 1)) AS [GroupBy1]
這是否看起來正確?我不像sql那麼好......但對我來說看起來效率不高。我錯過了什麼嗎?
是 'select count(*) from dbo.Users where [email protected] and IsActivated=1
' 效率不高?
第一個看上去效率低,但要記住,一個'EXISTS'將盡快匹配的記錄中發現停止。我對它的唯一問題是在第二個「WHEN」中重複查詢。我會期待它使用'ELSE cast(0 as bit)'。但是,查詢優化器應該只執行一次該查詢。 – cadrell0
@ cadrell0 - 優化器不僅會執行一次。參見[爲聚結不必要糟糕的表現(子查詢)](http://connect.microsoft.com/SQLServer/feedback/details/336002/unnecessarily-bad-performance-for-coalesce-subquery) –
@MartinSmith不說,優化器的一點? – cadrell0