简体   繁体   中英

SQL complicated join query

I have two tables: match(id.match, date, home, away) and team(id. team, name) . In match home and away are foreign keys to the team id . In my query, I want an output record with date of match, and name of these two teams.

I have tried:

SELECT m.date, m.home, m.away, t.name 
FROM `match` m
JOIN team t ON m.home = t.id_team 
ORDER BY m.date

But this outputs two records instead of one. Is it possible to do what I want with sql or I should just change the table's design?

I suspect you have a many to one relationship between your tables.

This might work depending on the table values:

 SELECT DISTINCT m.date, m.home, m.away, t.name 
 FROM   `match` m JOIN 
       team t ON m.home = t.id_team 
 ORDER BY m.date

Ok, i did 'deeper' research and find out the answer. Earlier i just asked wrong question. Thanks everyone for contribution!

Here is the solution:

SELECT m.date, m.home, m.away, t.name AS homename, te.name AS awayname
FROM `match` m 
JOIN team t ON m.home = t.id_team 
JOIN team te 
ON m.away = te.id_team ORDER BY m.date

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