MYSQL选择限制每个唯一值最后5个结果

时间:2019-03-29 09:46:42

标签: mysql

我目前正在从数据库中提取所有结果,其中结果是season ='19'。我想提取每个球队的前5个结果,其中赛季=“ 19”,但无法确定如何做到这一点。

我认为它将如下所示:

Select (each teamname from footballresults  and get last 5 games) Teamname, score1, score2 from footballresults where Code = '0101' and   Season = '19' and gamedate < CURDATE() 

当前代码为:

Select Teamname, score1, score2 from footballresults where Code = '0101' and   Season = '19' and gamedate < CURDATE() 

当前脚本将提取该赛季该联赛的所有结果,但从本质上讲,我想为每个团队循环播放并为每个团队获取最后5个结果,因此

目前,它可以获取每支球队的所有比赛(从DB中选择*赛季='19')

我只想返回每支球队的最近5场比赛,所以:

Select * from(
Team A Last 5 games
Team B Last 5 games
Team C Last 5 games
Team D Last 5 games
Team E Last 5 games
)

对于每个团队名称循环遍历并按gamedate仅选择最后3个游戏顺序(以下示例是我是否希望每个团队最后3个结果)-

+--------+---+---+--+
| Team a | 1 | 1 |  |
+--------+---+---+--+
| Team a | 4 | 1 |  |
+--------+---+---+--+
| Team a | 1 | 3 |  |
+--------+---+---+--+
| Team b | 0 | 0 |  |
+--------+---+---+--+
| Team b | 1 | 2 |  |
+--------+---+---+--+
| Team b | 2 | 0 |  |
+--------+---+---+--+

我正在使用MYSQL 5.6版

1 个答案:

答案 0 :(得分:0)

您可以使用子查询来获取最近日期的计数,并要求其小于5。

SELECT fbr1.teamname,
       fbr1.score1,
       fbr1.score2
       FROM footballresults fbr1
       WHERE fbr1.code = '0101'
             AND fbr1.season = '19'
             AND fbr1.gamedate < curdate()
             AND (SELECT count(*)
                         FROM footballresults fbr2
                         WHERE fbr2.code = '0101'
                               AND fbr2.season = '19'
                               AND fbr2.gamedate < curdate()
                               AND fbr2.teamname = fbr1.teamname
                               AND fbr2.gamedate > fbr1.gamedate) < 5;

但是,如果每天有多个游戏,则可能会失败。在这种情况下,您需要另一个条件来区分行,例如ID。例如:

   ...
                              AND (fbr2.gamedate > fbr1.gamedate
                                    OR fbr2.gamedate > fbr1.gamedate
                                       AND fbr2.id > fbr1.id) < 5;