我会使用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)我会在这个计算列上创建一个索引:
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)我会这样重写 EXISTS :
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