P粉0186537512023-09-03 09:55:42
I think you should consider a structure like this:
Teams(id,name) Seasons(id, year,begin_date,end_date) Games(id, date, season (外键), hometeam (外键), awayteam (外键), HomeTeamScore, AwayTeamScore)
This structure is not optimal either. In my personal opinion, you could go with a better structure:
Teams(id,name) Seasons(id, year,begin_date,end_date) Matches(id, date, season (外键), home_team (外键), away_team (外键)) Goals(id,team,game,player?)
The Goal table will be used to record every goal and you can then build match results from it, avoiding the use of the "HomeTeamScore" and "AwayTeamScore" fields.
As for the Stats table, you need to know who won the points, so let's stick with our final table structure:
Teams(id,name) Seasons(id, year,begin_date,end_date) Matches(id, date, season (外键), home_team (外键), away_team (外键), status) Goals(id,team,game,player?)
The status field value in Matches can be: ['1','X','2']
This way you can easily have everything to calculate your statistics, for example for team with 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';
You can use this as a starting point to build a slightly more complex query that uses the group by and group functions to calculate team statistics. Once you have successfully created a query like this, I recommend using Views
By the way, these queries you want to execute are not heavy, you don't necessarily need triggers, consider the database design first!
P粉9532317812023-09-03 00:42:53
A much simpler way than using triggers to maintain redundant data is to use a view; this is just a basic union sum:
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 );