2

我可以使用什么样的查询提示来提高 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 Lookups,而带有 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
4

1 回答 1

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'

至于明天会表演吗。
为了稳定,我将采用 UNION 而非 JOIN 或 OR。
使用 Union SQL 一次只做一个,查询优化器变得愚蠢的机会就更少了。

于 2013-05-07T15:40:02.383 回答