加入MySQL中另一个表中的第n个最高值

时间:2014-08-18 17:21:30

标签: mysql sql join greatest-n-per-group

我知道如何加入另一个表中列的MAX或MIN值,例如:

SELECT id, user_id, date_created, invite_date FROM user
INNER JOIN (
SELECT user_referral.user_id, MIN(user_referral.date_created) as invite_date
FROM user_referral
GROUP BY user_referral.user_id) AS invtable
ON user.id = invtable.user_id

但是,如何针对第n个最高或更低的user_referral.date_created值而不是 MAX MIN 执行此操作?

2 个答案:

答案 0 :(得分:3)

只需使用limit/offset

SELECT u.id, u.user_id, u.date_created, u.invite_date
FROM user u INNER JOIN
     (SELECT ref.*
      FROM user_referral ref
      GROUP BY ref.user_id
      ORDER BY ref.date_created
      LIMIT 1 OFFSET 8
     ) invtable
     ON u.id = invtable.user_id;

就像注释一样,这会返回第九行,因为偏移计数从0而不是1开始。

编辑:

现在我明白了。你可以这样做:

SELECT u.id, u.user_id, u.date_created, u.invite_date
FROM user u INNER JOIN
     (SELECT ref.*,
             (@rn := if(@uid = ref.user_id, @rn + 1,
                        if(@uid := ref.user_id, 1, 1)
                       )
             ) as rn
      FROM user_referral ref cross join
           (select @rn := 0, @uid := -1) vars
      ORDER BY ref.user_id, ref.date_created
     ) invtable
     ON u.id = invtable.user_id
WHERE rn = 8;

答案 1 :(得分:1)

您可以尝试使用LIMIT N语句然后像这样执行Max或Min(我在本例中使用了8):

SELECT id, user_id, date_created, invite_date FROM user
INNER JOIN (
SELECT user_id, MAX(user_referral.date_created) as invite_date
FROM (SELECT ref.user_id as user_id, MIN(ref.date_created) as invite_date
      FROM user_referral ref
      GROUP BY ref.user_id
      ORDER BY ref.date_created
      LIMIT 8)) AS invtable
ON user.id = invtable.user_id