P粉0186537512023-09-03 09:55:42
我认为你应该考虑这样的结构:
Teams(id,name) Seasons(id, year,begin_date,end_date) Games(id, date, season (外键), hometeam (外键), awayteam (外键), HomeTeamScore, AwayTeamScore)
这个结构也不是最佳的。 在我个人的意见中,你可以采用更好的结构:
Teams(id,name) Seasons(id, year,begin_date,end_date) Matches(id, date, season (外键), home_team (外键), away_team (外键)) Goals(id,team,game,player?)
Goal表将用于记录每个进球,然后你可以从中构建比赛结果,避免使用“HomeTeamScore”和“AwayTeamScore”字段。
至于Stats表,你需要知道谁赢得了积分,所以让我们坚持使用我们最后的表结构:
Teams(id,name) Seasons(id, year,begin_date,end_date) Matches(id, date, season (外键), home_team (外键), away_team (外键), status) Goals(id,team,game,player?)
Matches中的status字段值可以是:['1','X','2']
这样,你就可以轻松地拥有一切来计算你的统计数据,例如对于ID为12的球队:
Select * from Matches where home_team = 12 and result = '1'; Select * from Matches where away_team = 12 and result = '2'; Select * from Matches where home_team = 12 or away_team=12 and result='X';
你可以以此为起点,构建一个稍微复杂一点的查询,使用group by和group函数来计算球队的统计数据。 一旦你成功创建了这样的查询,我建议使用视图
顺便说一下,你想要执行的这些查询并不重,你不一定需要触发器,首先考虑好数据库设计!
P粉9532317812023-09-03 00:42:53
比使用触发器维护冗余数据要简单得多的方法是使用视图;这只是一个基本的联合求和:
create view stats as ( select season, team, sum(goalsscored) goalsscored, sum(goalsconcedded) goalsconcedded, sum(points) points from ( select season, hometeam team, HomeTeamScore goalsscored, AwayTeamScore goalsconcedded, case when HomeTeamScore > AwayTeamScore then 3 when HomeTeamScore=AwayTeamScore then 1 else 0 end points from game union all select season, awayteam team, AwayTeamScore goalsscored, HomeTeamScore goalsconcedded, case when AwayTeamScore > HomeTeamScore then 3 when AwayTeamScore=HomeTeamScore then 1 else 0 end points from game ) games group by season, team );