Top 1 with a left join

前端 未结 4 959
时光说笑
时光说笑 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:12

    Damir is correct,

    Your subquery needs to ensure that dps_user.id equals um.profile_id, otherwise it will grab the top row which might, but probably not equal your id of 'u162231993'

    Your query should look like this:

    SELECT u.id, mbg.marker_value 
    FROM dps_user u
    LEFT JOIN 
        (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 u.id = um.profile_id
         ORDER BY m.creation_date
        ) MBG ON MBG.profile_id=u.id 
    WHERE u.id = 'u162231993'
    

提交回复
热议问题