简体   繁体   中英

MySQL query to get multiple values from 1 table based on multiple columns from other table

I have this table structure (let's call this table teams ):

id | player1 | player2 | player3
1  | 13      | 25      | 50

And this (let's call this table players ):

id | pts
13 | 5
25 | 10
50 | 12

Is there a way to write one query to get the pts vlaue for each of the players from a row in table teams ?

For instance, if I wanted to get the pts value for player1, I would do something like:

select teams.id,players.pts from teams left join players on teams.player1=players.id

I need to do this for all 3 players at once (in reality, there are 18 players, not 3 - but the same principle should work).

I'm aware I can loop through them but that hardly seems like the optimal solution.

I think a better idea would be to have the following structure:

teams

team_id | name
----------------
1       | Team 1
2       | Team 2
3       | Team 3

players

player_id | pts
---------------
1         | 10
2         | 5
3         | 25

teams_players_xrefs

team_id | player_id
-------------------
1       | 1
1       | 2
2       | 3

And then use the following query:

SELECT
  player_id,
  pts
FROM
  teams_players_xrefs
INNER JOIN
  players USING (player_id)
WHERE
  team_id = 1

To get the following result:

player_id | pts
---------------
1         | 10
2         | 5

Here's the SQL Fiddle .

SELECT
  player1.pts AS player1_pts,
  player2.pts AS player2_pts,
  player3.pts AS player3_pts
FROM
  teams
  LEFT JOIN players AS player1 ON team.player1=player1.id
  LEFT JOIN players AS player2 ON team.player2=player2.id
  LEFT JOIN players AS player3 ON team.player3=player3.id
WHERE
   ...

You could left join the players table for each player, this would work but isn't really an ideal solution. Unfortunately due to your table structure is the best you can do.

It would be much better to create a mapping table, mapping teams with players. For example:

CREATE TABLE teams
(
  id INT,
  PRIMARY KEY(id)
 );

CREATE TABLE team_players
(
  team_id INT,
  player_id INT
)

This would allow you to then query by team_id and return all the players within that team easily.

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