从同一个表

时间:2017-07-19 13:31:05

标签: mysql

我有两个表团队和比赛:

╔═════════╗    ╔════════════╗
║  Teams  ║    ║  Matches   ║
╠═════════╣    ╠════════════╣
║ id (pk) ║    ║ id (pk)    ║
║ name    ║    ║ team1 (fk) ║
║ logo    ║    ║ team2 (fk) ║
╚═════════╝    ║ date       ║
               ║ score      ║
               ╚════════════╝

我想要检索这样的东西:

id   | Team 1      | Team 2       | Date                | Score
=====|=============|==============|=====================|==========
1    | Real Madrid | FC Barcelona | 2038-01-19 00:00:00 | 1-1 
2    | Sevilla     | Real Betis   | 2038-01-19 00:00:00 | 2-2

我用来检索数据的查询是:

SELECT DISTINCT team1, team2, date, score 
FROM Matches;

而且我不知道如何获得他们的id等于team1和team2外键的团队名称。

此前有一个类似的问题:How do you join on the same table, twice, in mysql?

在@AgapwIesu的帮助下:

SELECT Team1.name AS Team1Name, Team2.name AS Team2Name, Matches.date AS Date, Matches.score AS Score 
FROM Matches 
INNER JOIN Teams AS Team1 ON Team1.id = Matches.team1 
INNER JOIN Teams AS Team2 ON Team2.id = Matches.team2;

0 个答案:

没有答案