我有两个表,一个用于团队,另一个用于他们的时间表。
table teams
int teamId
varchar teamName
table sched
int schedId
date startDate
time startTime
int awayTeam
int homeTeam
如何编写获取两个团队名称的查询?
这个并不是很有效 -
select s.schedId,s.awayTeam,t.teamName,s.homeTeam,t.teamName
from sched s, teams t
where s.schedId=1
and t.teamId=s.homeTeam and t.teamId=s.awayTeam
我知道我的条款不正确,但它究竟应该是什么?
感谢
RD
答案 0 :(得分:2)
你在寻找这样的东西吗?
SELECT sched.*, at.teamName AS awayteam, ht.teamName AS hometeam FROM sched
JOIN teams AS at ON sched.awayteam = at.teamId
JOIN teams AS ht ON sched.hometeam = ht.teamId;
您可以多次连接一个表 - 但是您需要为它们使用别名,以形成正确的where子句。
请注意:FROM a JOIN b ON a.fk = b.id
具有与此相同的效果:FROM a,b WHERE a.fk = b.id