简体   繁体   中英

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. 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.

Persons' ID is in the form of home_id_1, away_id_1, home_id_2, and away_id_2.

Persons Table
id fname lname
1 Fred Bloggs
2 John Brown
3 Kevin Smith
4 James Kirk

Scores Table
Fixtures_ID home_id_1 away_id_1 home_id_2 away_id_2
1 1 2 3 4

My current SELECT statement is:

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
10/01/2016 Fred Bloggs John Brown Kevin Smith James Kirk

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

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

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