Top 1 with a left join

前端 未结 4 966
时光说笑
时光说笑 2020-12-22 23:44

Given the query below there might be multiple rows in dps_markers with the same marker key but we only want to join against the first. If I take this query and remove the t

4条回答
  •  不知归路
    2020-12-23 00:10

    Use OUTER APPLY instead of LEFT JOIN:

    SELECT u.id, mbg.marker_value 
    FROM dps_user u
    OUTER APPLY 
        (SELECT TOP 1 m.marker_value, um.profile_id
         FROM dps_usr_markers um (NOLOCK)
             INNER JOIN dps_markers m (NOLOCK) 
                 ON m.marker_id= um.marker_id AND 
                    m.marker_key = 'moneyBackGuaranteeLength'
         WHERE um.profile_id=u.id 
         ORDER BY m.creation_date
        ) AS MBG
    WHERE u.id = 'u162231993';
    

    Unlike JOIN, APPLY allows you to reference the u.id inside the inner query.

提交回复
热议问题