在引用外部表时从子查询连接到TOP 1

时间:2018-12-21 00:19:24

标签: sql sql-server tsql

我从这个查询开始,它运行良好:

SELECT 
    C.ContactSys
    , ... a bunch of other rows... 
FROM Users U
    INNER JOIN Contacts C ON U.ContactSys = C.ContactSys 
    LEFT JOIN UserWatchList UW ON U.UserSys = UW.UserSys 
    LEFT JOIN Accounts A ON C.AccountSys = A.AccountSys 
WHERE 
     C.OrganizationSys = 1012
     AND U.UserTypeSys = 2 
     AND C.FirstName = 'steve'

现在,我已收到此要求:

  

对于“访客搜索”返回的每个访客,请使用ContactSys,获取GuestLog表中该联系人的最新条目,然后从GuestLog表返回ABC和XYZ列。

我遇到了麻烦。我需要这样的东西(我认为)...

SELECT 
    C.ContactSys
    , GL.ABC
    , GL.XYZ
    , ... a bunch of other rows... 
FROM Users U
    INNER JOIN Contacts C ON U.ContactSys = C.ContactSys 
    LEFT JOIN UserWatchList UW ON U.UserSys = UW.UserSys 
    LEFT JOIN Accounts A ON C.AccountSys = A.AccountSys 
    LEFT JOIN (SELECT TOP 1 * FROM GuestLog GU WHERE GU.ContactSys = ????? ORDER BY GuestLogSys DESC) GL ON GL.ContactSys = C.ContactSys
WHERE 
     C.OrganizationSys = 1012
     AND U.UserTypeSys = 2 
     AND C.FirstName = 'steve'

不是那样,因为在JOIN上的子查询对外部表一无所知。

我一直在查看这些帖子及其答案,但是我很难将它们转换为我的需求:

SQL: Turn a subquery into a join: How to refer to outside table in nested join where clause?

Reference to outer query in subquery JOIN

Referencing outer query in subquery

Referencing outer query's tables in a subquery

1 个答案:

答案 0 :(得分:2)

如果这是您想要的逻辑,则可以使用OUTER APPLY

SELECT C.ContactSys, GL.ABC, GL.XYZ,
        ... a bunch of other columns ... 
FROM Users U JOIN
     Contacts C
     ON U.ContactSys = C.ContactSys LEFT JOIN
     UserWatchList UW 
     ON U.UserSys = UW.UserSys LEFT JOIN
     Accounts A
     ON C.AccountSys = A.AccountSys OUTER APPLY
     (SELECT TOP 1 gl.*
      FROM GuestLog gl
      WHERE gl.ContactSys = C.ContactSys
      ORDER BY gl.GuestLogSys DESC
     ) GL
WHERE C.OrganizationSys = 1012 AND
      U.UserTypeSys = 2 AND
      C.FirstName = 'steve'