This is a really common use case but I’ve never known the best way of doing it. Say I have two tables
team table
– id
– team name
players table
– id
– team_id
– player_name
Say in the output html I want to show headings of the teams, and underneath each team the respective players:
Team 1
– bob
– jon
Team 2
– ken
– jason
Previously I’ve always used a select statement for the teams, and while looping thru the results, do another select statment where the foreign key would equal the ID of the current row of the outer query. Is this a dumb, non-efficient way of doing it? What’s the standard way of doing something like this? I could use join but I’m guess I would need to add some logic to only show the team heading once. I’m using php+mysql.
Generally looping through one result set and querying for more info inside the loop isn’t a good idea. It’s a best to avoid database queries in loops if possible. As you suggest a JOIN would work here:
There are a number of ways you could process the results in PHP. You could loop through the results and add them to an array
You can then loop through the array and output the results how you want.
Or you could just loop directly through the db results and output them as you go storing the team name and only outputting it when it changes. I’d recommend the former solution. It’s cleaner and abstracted better.