我會用EXISTS(SELECT ...)
代替(SELECT COUNT(*) FROM ...) > 0
:
CASE
WHEN IsPromoted = 1 THEN 'true' -- See Martin Smith's comment
WHEN EXISTS(SELECT * FROM .... dbo.Payments ...) THEN 'true'
ELSE 'false'
END
如果性能是非常重要的話,我會測試解決方案:
1)我想創建一個計算列:
ALTER TABLE dbo.Payments
ADD ColumnA AS DATEADD(day, DurationDays, PaymentReceived);
GO
2)和我會create an index on this computed column:
SET NUMERIC_ROUNDABORT OFF;
SET ANSI_NULLS ON;
SET ANSI_PADDING ON;
SET ANSI_WARNINGS ON;
SET ARITHABORT ON;
SET CONCAT_NULL_YIELDS_NULL ON;
SET QUOTED_IDENTIFIER ON;
CREATE /*UNIQUE*/ INDEX IX_Payments_EventId_ColumnA
ON dbo.Payments(EventId, ColumnA);
GO
3)我想重寫因此存在:
CASE
WHEN IsPromoted = 1 THEN 'true' -- See Martin Smith's comment
WHEN EXITS(SELECT * FROM dbo.Payments
WHERE EventId = dbo.Events.EventCode
AND ColumnA > GETDATE()) THEN 'true'
ELSE 'false'
END
另外,我想嘗試以下指標:
CREATE /*UNIQUE*/ INDEX IX_Payments_EventId_#_DurationDays_PaymentReceived
ON dbo.Payments(EventId)
INCLUDE(DurationDays, PaymentReceived);
GO
你應該做一個左連接而不是這個Count> 0,但是我不能確定,直到你包含你的整個查詢。 – EkoostikMartin