该索引可能会有所帮助,但请记住,没有免费的午餐(必须维护索引,因此这会影响您的插入/更新/删除工作量):
CREATE NONCLUSTERED INDEX unread_emails
ON dbo.MemberMail(ToMemberID)
INCLUDE (MemberMailID)
WHERE ToReadFlag = 0
AND ToDeletedFlag = 0
AND FromDeletedFlag = 0
AND OnHold = 0
AND ToArchivedFlag = 0;
现在您的查询可以说:
SELECT TOP (1) MemberMailID
FROM dbo.MemberMail -- dbo prefix
WITH (INDEX (unread_emails)) -- in case you need to force, though you should not
WHERE ToMemberID = 102
AND ToReadFlag = 0
AND ToDeletedFlag = 0
AND FromDeletedFlag = 0
AND OnHold = 0
AND ToArchivedFlag = 0
ORDER BY ToMemberID; -- ORDER BY is important!
如果您根据查询更改其中一些标志的值,您可以尝试将这些列添加到索引的键而不是过滤器,例如,假设有时您检查OnHold = 0
并且有时OnHold = 1
:
CREATE NONCLUSTERED INDEX unread_emails
ON dbo.MemberMail(ToMemberID, OnHold)
INCLUDE (MemberMailID)
WHERE ToReadFlag = 0
AND ToDeletedFlag = 0
AND FromDeletedFlag = 0
AND ToArchivedFlag = 0;
您可能还想尝试使用MemberMailID
in 代替INCLUDE
. 例如:
CREATE NONCLUSTERED INDEX unread_emails
ON dbo.MemberMail(ToMemberID, MemberMailID)
WHERE ToReadFlag = 0
AND ToDeletedFlag = 0
AND FromDeletedFlag = 0
AND OnHold = 0
AND ToArchivedFlag = 0;
这些差异可能对您的数据和使用模式无关紧要,但您将能够比我们猜测的更容易测试差异。