MYSQL查询以显示客队名称和主队名称

时间:2019-03-20 14:41:15

标签: mysql

我有两个桌子。
游戏包括Date,hteam,ateam,hscore,ascore。
团队包括id,tname。

此查询:

SELECT
    games.DATE,
    teams.tname AS "Away",
    games.ascore AS "A Score",
    games.hteam AS "Home",
    games.hscore AS "H Score"
FROM
    games
INNER JOIN teams ON games.ateam = teams.id
LEFT OUTER JOIN teams AS t
ON
    games.hteam = t.tname
ORDER BY
    games.DATE ASC

最终产生此输出:

DATE Ascending 1        Away        A Score Home    H Score     
2008-01-01 20:00:00     Saxons      2       3       0
2008-01-01 20:00:00     Spurs       0       1       1
2008-01-08 20:00:00     Saxons      1       2       2
2008-01-08 20:00:00     Celtics     1       1       1

我的问题是如何使主队显示为其名称而不是其ID,因此输出为:

DATE Ascending 1        Away        A Score Home        H Score     
2008-01-01 20:00:00     Saxons      2       Celtics     0
2008-01-01 20:00:00     Spurs       0       Wanderers   1
2008-01-08 20:00:00     Saxons      1       Spurs       2
2008-01-08 20:00:00     Celtics     1       Wanderers   1

2 个答案:

答案 0 :(得分:1)

您需要对“ teams”表进行另一个联接才能获得结果。 因此:

SELECT
    games.DATE,
    teams_away.tname AS "Away",
    games.ascore AS "A Score",
    teams_home.tname AS "Home",
    games.hscore AS "H Score"
FROM
    games
INNER JOIN teams teams_away ON games.ateam = teams_away.id
INNER JOIN teams teams_home ON games.hteam = teams_home.id
ORDER BY
    games.DATE ASC

答案 1 :(得分:0)

这是一种使用子查询来编写查询的方法,它避免了联接:

SELECT
    games.DATE,
    (SELECT tname FROM teams WHERE teams.id = games.hteam) AS "Away",
    games.ascore AS "A Score",
    (SELECT tname FROM teams WHERE teams.id = games.ateam) AS "Home",
    games.hscore AS "H Score"
FROM
    games
ORDER BY
    games.DATE ASC