我可以使用哪种查询提示来提高OR查询的性能。
以下两个查询单独立即运行并返回0行。
SELECT * FROM AuditInfo ai
WHERE (ai.AppointmentIdForChange = 60231)
and ai.objectname = 'dbo.Appointments'
SELECT * FROM AuditInfo ai
WHERE (ai.AppointmentIdForKey = 60231)
and ai.objectname = 'dbo.Appointments'
AuditInfo是一个视图。
但是以下查询将永远运行(10分钟以上)
SELECT * FROM AuditInfo ai
WHERE (ai.AppointmentIdForKey= 60231 OR ai.AppointmentIdForChange = 60231)
and ai.objectname = 'dbo.Appointments'
我该如何改进?我可以使用查询提示吗?
在估计的执行计划中,我可以看到各个查询使用Key Looks,而带有OR语句的查询使用Index Seeks(占用了74%的成本)。
更新:
AuditInfo视图定义如下:
ALTER VIEW AuditInfo
AS
SELECT
ae.Id
,ae.AuditDateTime AS DateTime
,ae.ChangeTypeId
,ae.ObjectName
,aek.KeyName
,aek.KeyValue
,aek.KeyValueNumeric
,ae.UserId
,ae.HostName
,ae.ServerName
,aec.OldValue
,(SELECT TOP 1 aecNewValue.OldValue AS Value
FROM dbo.AuditEntries aeNewValue
JOIN dbo.AuditEntryKeyValues aekNewValue ON aeNewValue.Id = aekNewValue.AuditEntryId AND aek.KeyName = aekNewValue.KeyName AND aek.KeyValueNumeric = aekNewValue.KeyValueNumeric
JOIN dbo.AuditEntryChanges aecNewValue ON aeNewValue.Id = aecNewValue.AuditEntryId AND aec.ColumnName = aecNewValue.ColumnName
WHERE aeNewValue.ChangeTypeId IN (0, 1) AND aeNewValue.AuditDateTime > ae.AuditDateTime AND aeNewValue.ObjectName = ae.ObjectName
ORDER BY aeNewValue.AuditDateTime
) AS NewValue
,appointmentForKey.AppointmentId AS AppointmentIdForKey, appointmentForChange.AppointmentId AS AppointmentIdForChange
FROM dbo.AuditEntries ae
JOIN dbo.AuditEntryKeyValues aek on ae.Id = aek.AuditEntryId
LEFT JOIN dbo.AuditEntryChanges aec on ae.Id = aec.AuditEntryId AND aec.ColumnName IN ('PatientId', 'AppointmentId')
-- Get AppointmentId
LEFT JOIN dbo.Appointments appointmentForKey ON aek.KeyName = 'AppointmentId' AND aek.KeyValueNumeric = appointmentForKey.AppointmentId
LEFT JOIN dbo.Appointments appointmentForChange ON aec.ColumnName = 'AppointmentId' AND aec.OldValueNumeric = appointmentForChange.AppointmentId
GROUP BY ae.Id, ae.AuditDateTime, ae.UserId, ae.ChangeTypeId, ae.ObjectName, ae.HostName, ae.ServerName, aek.KeyName, aek.KeyValue, aek.KeyValueNumeric, aec.OldValueNumeric, aec.OldValue, aec.ColumnName
,appointmentForKey.AppointmentId, appointmentForChange.AppointmentId
答案 0 :(得分:1)
我知道您要求提供查询提示,但您可以将其作为两个带联合的查询
运行SELECT * FROM AuditInfo ai
WHERE (ai.AppointmentIdForChange = 60231)
and ai.objectname = 'dbo.Appointments'
UNION
SELECT * FROM AuditInfo ai
WHERE (ai.AppointmentIdForKey = 60231)
and ai.objectname = 'dbo.Appointments'
至于它将在明天表演 为了稳定,我会通过JOIN或OR取一个UNION 使用Union SQL可以一次执行一个,并且查询优化器获得愚蠢的可能性更小。