我有一个带有桌子比赛的体育俱乐部的比赛日历 'ID', '家', '离开', '得分'
在主页和离开栏中是球队ID
团队名称位于Teams表中 'id','name','logo'
我正在生成表格 从匹配日期asc
中选择*然后我在输出中得到了ID 我可以使用像这样的连接 选择*来自匹配,团队Matches.home = Teams.id,但这只能将一个ID解析为名称。 我怎样才能解决这个问题以获得两个名字(家庭和远方? 仅供参考:我将它与PHP结合使用
答案 0 :(得分:0)
使用JOIN
语法。像这样:
SELECT
Matches.id,
Matches.score,
TeamHome.name AS HomeTeam,
TeamAway.name AS AwayTeam
FROM
Matches
JOIN Teams AS TeamHome
ON Matches.home=TeamHome.id
JOIN Teams AS TeamAway
ON Matches.away=TeamAway.id
或者如果home
和away
可以为空,那么使用LEFT JOIN
可能是有意义的。像这样:
SELECT
Matches.id,
Matches.score,
TeamHome.name AS HomeTeam,
TeamAway.name AS AwayTeam
FROM
Matches
LEFT JOIN Teams AS TeamHome
ON Matches.home=TeamHome.id
LEFT JOIN Teams AS TeamAway
ON Matches.away=TeamAway.id
答案 1 :(得分:0)
首先使用JOIN
,您应该使用ON
子句,而不是WHERE
。其次 - 您可以多次加入同一张桌子:
SELECT * FROM Matches
JOIN Teams as Home ON Matches.home = Home.id
JOIN Teams as Away ON Matches.away = Away.id