[英]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
): 我有这个表结构(我们称这个表为
teams
):
id | player1 | player2 | player3
1 | 13 | 25 | 50
And this (let's call this table players
): 这(让我们将此表称为
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
? 有没有写一个查询来获取的方式
pts
vlaue为每个从表中的一行球员teams
?
For instance, if I wanted to get the pts
value for player1, I would do something like: 例如,如果我想获取player1的
pts
值,则可以执行以下操作:
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). 我需要同时为所有3位玩家执行此操作(实际上,有18位玩家,而不是3位-但相同的原理应该起作用)。
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_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 . 这是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. 您可以离开每个玩家的
players
表,这可以工作,但实际上并不是理想的解决方案。 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. 然后,您可以通过team_id进行查询,并轻松返回该团队中的所有球员。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.