I am trying to show some simple results of a computer game and make it easier to repeat the results line by line in my code. I want all the relevant data for each game to be in each record, so I can print it all on one line, for example:
- Team A (score 45 ) vs. Team B (score 55 ), game duration: 5 min
- Team C (score 60 ) vs Team D (score 65 ), game duration: 4.3 min
So, for the game there are two teams that play with each other, and each of them receives a score at the end of the game. Essentially, each game table has two rows in the games_teams table.
Here is my diagram:
Here is my table data:
Here's the result I'm trying to achieve, so I can easily iterate over the results and display them on the page:
I managed to achieve this with some horrible SQL and lots of subqueries like:
SELECT games.game_id, game_name, game_duration, (SELECT team_id FROM games_teams WHERE games.game_id = games_teams.game_id LIMIT 0, 1) AS team_id_a, (SELECT team_id FROM games_teams WHERE games.game_id = games_teams.game_id LIMIT 1, 1) AS team_id_b, (SELECT teams.team_name FROM games_teams INNER JOIN teams ON games_teams.team_id = teams.team_id WHERE games.game_id = game_id LIMIT 0, 1) AS team_name_a, (SELECT teams.team_name FROM games_teams INNER JOIN teams ON games_teams.team_id = teams.team_id WHERE games.game_id = game_id LIMIT 1, 1) AS team_name_b, (SELECT team_score FROM games_teams WHERE games.game_id = games_teams.game_id LIMIT 0, 1) AS team_score_a, (SELECT team_score FROM games_teams WHERE games.game_id = games_teams.game_id LIMIT 1, 1) AS team_score_b FROM games
The problem with this method will be slow and it does not scale. I also need to pull other game statistics from the games_teams table so that there are even more subqueries.
Another method I tried was:
I achieved this with the following SQL:
SELECT games.game_id, game_name, game_duration, teams.team_id, team_name, team_score FROM games INNER JOIN games_teams ON games.game_id = games_teams.game_id INNER JOIN teams ON games_teams.team_id = teams.team_id
Now this method will be more difficult to execute in the code, since the corresponding data for each game will be in two different records. I would have to build the first part of the line, and then move on to the next iteration of the loop and print the next part. Then run it again for the next game, I try to display all the information on one line, for example:
Team A (score 45) versus Team B (score 55), game duration: 5 minutes
So why do I think it would be easier if everything was on one record. Is there a way to do this nicely, and so it scales if I need more columns in the games_teams table?
Here's a pastebin link with the database code if you need to recreate it.
Any help is much appreciated, thanks!