mysql取最后6条数据,在MySQL数据库中获取每个团队的最后6条记录

I have a MySQL database containing soccer results and want to retrieve just a specific subset of that data.

The data consists of one table containing MatchDate, HomeTeam, AwayTeam, HomeGoals, AwayGoals

How can I retrieve a subset of this data that contains the last 6 matches that each team has been involved in?

Whilst I can do this for a single team, how do I get a single subset that contains the last 6 matches for each team in the table? (I am not worried that the subset may contain some duplicates).

解决方案

Here's one way to do it with a user-defined variable:

select MatchDate, HomeTeam, AwayTeam, HomeGoals, AwayGoals

from (

select

MatchDate, HomeTeam, AwayTeam, HomeGoals, AwayGoals,

@teamCounter:=IF(@prevHome=HomeTeam,@teamCounter+1,1) teamCounter,

@prevHome:=HomeTeam

from yourtable

join (select @teamCounter:=0) t

order by HomeTeam, MatchDate desc

) t

where teamCounter <= 6

And here is the update from the Fiddle:

select team, MatchDate, HomeTeam, AwayTeam, HomeGoals, AwayGoals

from (

select

team, yourtable.MatchDate, HomeTeam, AwayTeam, HomeGoals, AwayGoals,

@teamCounter:=IF(@prevHome=team,@teamCounter+1,1) teamCounter,

@prevHome:=team

from yourtable

join (

select distinct matchdate, hometeam team

from yourtable

union

select distinct matchdate, awayteam

from yourtable

) allgames on yourtable.matchdate = allgames.matchdate

and (yourtable.hometeam = allgames.team or yourtable.awayteam = allgames.team)

join (select @teamCounter:=0) t

order by team, yourtable.MatchDate desc

) t

where teamCounter <= 6

order by team

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值