简体   繁体   中英

sql - multiple FK columns from same table

I have two tables, one for teams and other for their schedules.

table teams
int teamId
varchar teamName

table sched
int schedId
date startDate
time startTime
int awayTeam
int homeTeam

How do I write the query that get the names for both teams?

This one doesn't quite do the trick -

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

I know my and clause is incorrect, but what should it really be?

Thanks
RD

Are you searching for something like this?

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;

You can join one table several times - but you will need to use aliases for them, to form correct where-clauses.

Notice, that this: FROM a JOIN b ON a.fk = b.id has the same effect as this: FROM a,b WHERE a.fk = b.id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM