我正在编写一个 SQL 查询,用于从多个表中提取记录,以便向用户发送更新或添加新值的电子邮件通知。
在下面的 SQL 查询中,我正在获取在各个表中更新的所有记录,但是我想在每个 LEFT JOIN 状态中为表的AssociatedRecordID
列添加一个条件检查/JOIN,NotificationQueue
这样我只会从每个选择表中提取匹配的记录来增加查询执行的性能。
例如:
LEFT JOIN Note nt WITH(NOLOCK) ON op.OpportunityID = nt.RecordID AND nt.NoteID = nq.AssociatedRecordID
这里我想nq.AssociatedRecordID
用于加入AND nt.NoteID = nq.AssociatedRecordID
询问:
SELECT ops.* FROM NotificationQueue nq
INNER JOIN (
SELECT op.OpportunityID, op.Name AS [OpportunityName], ua.Email AS OwnerEmail, nt.NoteID, nt.Note,
tks.TaskID, tks.ActivityType, ua.FirstName, ua.LastName, FORMAT(getdate(), 'M/dd/yyyy, hh:mm:ss tt') AS [datetime],
lead.LeadID, lead.LeadName
FROM Opportunity op WITH(NOLOCK)
INNER JOIN UserAccount ua WITH(NOLOCK) on op.owner = ua.UserID
LEFT JOIN Note nt WITH(NOLOCK) ON op.OpportunityID = nt.RecordID AND nt.EntityID = 4 -- OPPORTUNITY
LEFT JOIN (
SELECT t.TaskID, t.TaskTypeID, t.OpportunityID, tt.Description AS [ActivityType] FROM Task t WITH(NOLOCK)
INNER JOIN TaskType tt ON t.TaskTypeID = tt.TaskTypeID
) tks ON op.OpportunityID = tks.OpportunityID
LEFT JOIN (
SELECT l.LeadID, l.Topic AS [LeadName], lo.AssociatedOpportunityId FROM LeadOpportunity lo WITH(NOLOCK)
INNER JOIN Lead l ON lo.ParentLeadId = l.LeadID
WHERE l.Active = 1
) lead ON op.OpportunityID = lead.AssociatedOpportunityId
WHERE op.Active = 1
) ops ON nq.RecordID = ops.OpportunityID
WHERE nq.Processed = 'N'
我从上面的查询中得到了预期的记录,但我想在所有语句中使用 Table 的AssociatedRecordID
列以获得更好的性能,任何建议我应该如何实现同样的效果将不胜感激。NotificationQueue
LEFT JOIN
您可能希望将EXISTS 运算符与子查询一起使用,但在不同的情况下服务,在您的情况下,将
NotificationQueue
表向下移动到子查询可以让您执行您正在寻找的连接,以下是相同的示例:根据评论,以下是 last 的示例
LEFT JOIN
: