简体   繁体   中英

Selecting all rows from one table grouped by unique values from another table

I have simple database with two tables.

In teams table there are columns team and id .
players table has columns player_name , player_age , position and team_id .

team_id in players table is foreign key that refers to team_name in teams table.

I want to display this information in HTML table using PHP where I will have header with team_name , player_name and player_age .

I need only unique team_name values because I want to echo whole table using while loop so I need them to only echo once in header. I hope this makes sense.

My problem is, I don't know how to write a query which will return distinct team_name values from teams table but all players and age info from players table.

I've tried using joins but I always end up having same number of team_name values as player_name values.

I do this for exercise only so any security issues and stuff like that are not my concern right now.

assuming you want show the relation for the team with id = 3 you can use a join as

select t.team_name, p.player_name, p.player_age
from teams t 
inner join players p on p.team_id = t.id
and t.id = 3

or if you want the relation based on team name

select t.team_name, p.player_name, p.player_age
from teams t 
inner join players p on p.team_id = t.id
and t.team_name = 'your_preferred_team_name'

if you want all team in a single query then

select t.team_name, p.player_name, p.player_age
from teams t 
inner join players p on p.team_id = t.id
Order by t.id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM