[英]Two columns refer to one id in another table
I've been trying to work out the following but I can't get my head around it. 我一直在尝试解决以下问题,但我无法解决。
I need to match up the player IDs shown within the scores table to the persons table, and return the relevant person's name. 我需要将分数表中显示的玩家ID与人员表进行匹配,并返回相关人员的姓名。 Below is a condensed version of the tables showing the core parts of what's required.
以下是表格的精简版,显示了所需内容的核心部分。
Details will be returned based on the fixtures ID, so whatever person's ID falls on the same row I need to get their names. 详细信息将根据灯具ID返回,因此无论任何人的ID都在同一行,我需要获取其姓名。
Persons' ID is in the form of home_id_1, away_id_1, home_id_2, and away_id_2. 人员ID的格式为home_id_1,away_id_1,home_id_2和away_id_2。
Persons Table
人数表
id fname lnameid fname lname
1 Fred Bloggs1弗雷德·博格斯
2 John Brown2约翰·布朗
3 Kevin Smith3凯文·史密斯
4 James Kirk4詹姆斯·柯克
Scores Table
分数表
Fixtures_ID home_id_1 away_id_1 home_id_2 away_id_2灯具ID-home_id_1 away_id_1 home_id_2 away_id_2
1 1 2 3 41 1 2 3 4
My current SELECT statement is: 我当前的SELECT语句是:
SELECT scores.fixture_id, scores.match_date, players.fname, players.lname,
scores.home_id_1, scores.away_id_1, scores.home_id_2, scores.away_id_2
FROM scores, players
WHERE fixture_id = 1
Output should be something along the lines of: 输出应该类似于以下内容:
Match Date Home Player 1 v Away Player 1, Home Player 2 v Away Player 2
比赛日期 主场球员1 v 客场球员1, 主场球员2 v 客场球员2
10/01/2016 Fred Bloggs John Brown Kevin Smith James Kirk2016/10/01弗雷德·博格斯约翰·布朗凯文·史密斯詹姆斯·柯克
Hope this makes sense, and any help is greatly appreciated. 希望这是有道理的,任何帮助将不胜感激。
Thanks, 谢谢,
Dan. 担。
Try something like following 尝试以下操作
SELECT scores.fixture_id,
scores.match_date,
CONCAT(p1.fname, p1.lname),
CONCAT(p2.fname, p2.lname),
CONCAT(p3.fname, p3.lname),
CONCAT(p4.fname, p4.lname),
s.home_id_1,
s.away_id_1,
s.home_id_2,
s.away_id_2
FROM scores s
INNER JOIN players p1 ON s.home_id_1 = p1.id
INNER JOIN players p2 ON s.away_id_1 = p2.id
INNER JOIN players p3 ON s.home_id_2 = p3.id
INNER JOIN players p4 ON s.away_id_2 = p4.id
WHERE s.fixture_id = 1
Maybe you need to use LEFT JOIN if you expect to have null values 如果您希望使用空值,则可能需要使用LEFT JOIN
You need to join to the players table four times, once for each column you want to match with it. 您需要四次加入玩家表,对于要与之匹配的每一列一次。 Something like this:
像这样:
SELECT
scores.fixture_id,
scores.match_date,
players1.fname + ' ' + players1.lname,
players2.fname + ' ' + players2.lname,
players3.fname + ' ' + players3.lname,
players4.fname + ' ' + players4.lname,
FROM
scores,
INNER JOIN players players1 ON scores.home_id_1 = players1.id
INNER JOIN players players2 ON scores.home_id_2 = players2.id
INNER JOIN players players3 ON scores.away_id_1 = players3.id
INNER JOIN players players4 ON scores.away_id_2 = players4.id
WHERE
scores.fixture_id = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.