晚上,我不确定如何标题我的问题,但我有一个让我发疯的问题,我似乎无法找到答案,所以我希望你善良的人们可以指出我正确的方向。
我目前正在制作一个体育预测网站,以了解有关PHP和SQL的更多信息。所以我有以下数据库......
Teams
id | team_name | active
1 team 1 1
2 team 2 0
3 team 3 1
Matches
id | hometeam | homescore | awayteam | awayscore
1 3 1 4 0
2 5 2 1 3
3 1 0 3 2
无论如何要简单地说。我想要的是在Teams表中查询团队和远程团队中的团队ID。所以到目前为止我已经得到了这个:
SELECT * FROM Matches LEFT JOIN Teams AS home ON Matches.hometeam = home.id LEFT JOIN Teams AS away ON Matches.awayteam = away.id
实际上它确实做到了,除了它让我留下2列名为" team_name"一个是主队,一个是客队。
所以我的问题是,我可以将列别名/重命名为' home'并且'远离'或者有没有办法在我的页面上我可以区分这两者?例如,我有$row['team_name']
但是如何将其指向正确的team_name列?如果这是有道理的。
非常感谢任何向我指明正确方向的帮助,谢谢。
答案 0 :(得分:1)
SELECT home.team_name as home_team, away.team_name as away_team FROM Matches LEFT JOIN Teams AS home ON Matches.hometeam = home.id LEFT JOIN Teams AS away ON Matches.awayteam = away.id
答案 1 :(得分:1)
指定列名而不是使用SELECT *
SELECT home.team_name AS home_team, away.team_name AS away_team, homescore, awayscore
FROM Matches
LEFT JOIN Teams AS home ON Matches.hometeam = home.id
LEFT JOIN Teams AS away ON Matches.awayteam = away.id
您should not use SELECT *在您的查询中,出于多种原因在其他地方进行了彻底解释。