在mysql中选择具有最大时间戳的多个记录

时间:2011-07-15 02:53:20

标签: php mysql greatest-n-per-group

这是最新的:一个子查询,用于选择符合我的条件的指定日期之前的所有记录,然后尝试按用户ID对结果进行分组并按等级排序

它似乎没有工作。请注意,也可能有多个人处于同一级别。

SELECT *
  FROM (SELECT users.userid as userid,
               users.name as name,
               leagues.league as league,
               leagues.datestamp AS datestamp,
               ranking.ranking as ranking,
               user_profiles.profile_pic as profile_pic,
               user_profiles.team as team
          FROM users
     LEFT JOIN leagues ON users.userid = leagues.userid
     LEFT JOIN ranking ON users.userid = ranking.userid
     LEFT JOIN user_profiles ON users.userid=user_profiles.userid
         WHERE (leagues.datestamp <= '{$date}' 
           AND leagues.ladder = '3'  
           AND ranking.ladder = '3')
      ORDER BY datestamp DESC) as t1
GROUP BY userid
ORDER BY ranking

1 个答案:

答案 0 :(得分:1)

你试过一个简单的子查询吗?

SELECT users.userid as userid,
       users.name as name,
       leagues.league as league,
       leagues.datestamp AS datestamp,
       ranking.ranking as ranking,
       user_profiles.profile_pic as profile_pic,
       user_profiles.team as team
FROM   users
LEFT JOIN leagues ON users.userid = leagues.userid
LEFT JOIN ranking ON users.userid = ranking.userid
LEFT JOIN user_profiles ON users.userid=user_profiles.userid
WHERE  leagues.datestamp = (
    SELECT MAX(datestamp)
    FROM   leagues
    WHERE  leagues.ladder = '3'
      AND  leagues.datestamp <= '{$date}'
)
  AND  leagues.ladder = '3'  
  AND  ranking.ladder = '3'
ORDER BY ranking