使用外部查询的列联接子查询

时间:2020-02-04 13:35:02

标签: sql sql-server tsql join sql-server-2017

这是我的联接查询:

Select * 
    From MetricAlertMonitorings maa
        Left Join (
                    Select Top 1 *
                        From [dbo].MetricAlertMonitoringsDeliveredLog
                            Where maa.MetricAlertMonitoringID = [dbo].MetricAlertMonitoringsDeliveredLog.MetricAlertMonitoringID
                            Order By DeliveredDateTime asc
                ) mdl
                    ON maa.MetricAlertMonitoringID = mdl.MetricAlertMonitoringID
                Left Join (
                    Select Top 1 *
                        From [dbo].MetricAlertMonitoringsAcknowledgedLog
                            Where maa.MetricAlertMonitoringID = [dbo].MetricAlertMonitoringsAcknowledgedLog.MetricAlertMonitoringID
                            Order By MetricAlertMonitoringsStatusID asc, AcknowledgedDateTime asc
                ) mal
                    ON maa.MetricAlertMonitoringID = mal.MetricAlertMonitoringID

但是以某种方式,查询无法识别列maa.MetricAlertMonitoringID。我收到错误消息:

Msg 4104, Level 16, State 1, Line 7
The multi-part identifier "maa.MetricAlertMonitoringID" could not be bound.
Msg 4104, Level 16, State 1, Line 14
The multi-part identifier "maa.MetricAlertMonitoringID" could not be bound.

我需要将我的查询作为子查询加入。知道我该如何解决吗?

1 个答案:

答案 0 :(得分:3)

联接的子查询无法引用外部查询中的列,因此会出现错误。我认为您应该改用OUTER APPLY

Select * 
From MetricAlertMonitorings maa
outer apply (
    Select Top 1 *
    From [dbo].MetricAlertMonitoringsDeliveredLog
    Where maa.MetricAlertMonitoringID = [dbo].MetricAlertMonitoringsDeliveredLog.MetricAlertMonitoringID
    Order By DeliveredDateTime asc
) mdl
outer apply (
    Select Top 1 *
    From [dbo].MetricAlertMonitoringsAcknowledgedLog
    Where maa.MetricAlertMonitoringID = [dbo].MetricAlertMonitoringsAcknowledgedLog.MetricAlertMonitoringID
    Order By MetricAlertMonitoringsStatusID asc, AcknowledgedDateTime asc
) mal