After inserting data in MySQL, conditionally increase two values
P粉937382230
2023-09-02 10:52:17
<p>I currently have the following three tables in a football database:</p>
<pre class="brush:php;toolbar:false;">teams(name)
season(name, beginning, end)
game(id, Date, season, hometeam, awayteam, HomeTeamScore, AwayTeamScore)
(hometeam, awayteam and season are foreign keys)</pre>
<p>Now I want to have a new table that records the goals scored and goals conceded by each team, as well as the points they earned in each season (one point for each draw, three for each win) . This will make ranking easy to obtain. </p>
<p>I considered creating a table like this:</p>
<pre class="brush:php;toolbar:false;">stats(season, team, goalsscored, goalsconcedded, points)</pre>
<p>Then every time a new match is inserted, I also update this table. This table will contain one row for each team's season combination. I'm not sure if this is the best solution as I know I'm introducing redundancy, but since this information needs to be calculated frequently I thought it might be useful. I want to create a trigger to update this information, but I don't really know how to do it: depending on which team is participating in the match, I need to update two rows in the stats table, and depending on whether they are home or away, I need Update them with different values. </p>
<p>Ideally, this trigger should create an entry in this new table if the team hasn't inserted a record for the season the game belongs to, but I'm not even sure if such a condition is possible in MySQL.
I know I didn't provide any testing of what I did, but that's because I really couldn't find a similar request online (or more generally, one that makes it easy to query the information I need). </p>
<p>Also, I'm open to better ideas on how to handle this situation. </p>
I think you should consider a structure like this:
This structure is not optimal either. In my personal opinion, you could go with a better structure:
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:
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:
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!
A much simpler way than using triggers to maintain redundant data is to use a view; this is just a basic union sum: