tags:

views:

312

answers:

4

I have 2 tables like this:
[games]
gameid
hometeamid
awayteamid
score

and

[teams]
teamid
teamname

How would i create a query to output something like:
[home team][away team][score]
49ers chargers 28-17

You see, i need to resolve 2 team names with 2 team ids within the same table and output just the names. Thanks in advance for your help!

A: 

This should work for you:

select t1.teamname, t2.teamname, g.score
from games as g
     left outer join team as home_team
       on g.hometeamid = home_team.id
     left outer join team as away_team
       on g.awayteamid = away_team.id
allyourcode
A: 
SELECT (SELECT teams.teamname FROM teams WHERE teams.teamid=games.awayteamid) AS awayteam,     
(SELECT teams.teamname FROM teams WHERE teams.teamid=games.hometeamId) AS hometeam, score 
FROM games 
WHERE gameid = '1'
Mark
+1  A: 
SELECT
  ht.TeamName AS HomeTeam,
  vt.TeamName AS AwayTeam,
  g.Score
FROM
  games g INNER JOIN teams ht
    on g.hometeamid = ht.teamid
  INNER JOIN teams vt
    on g.awayteamid = vt.teamid

I'd suggest naming the tables "game" and "team" - as I'm not a fan of plural table names. I'm not alone in this opinion, but it's really a style/preference thing.

codemonkey
I did it this way very similar SELECT t1.teamname, t2.teamname, score FROM games, teams t1, teams t2 WHERE games.hometeamid = t1.teamid AND games.awayteamid = t2.teamid
Justin Giboney
A: 

Thanks for the quick responses, codemonkey this is exactly what i needed. Thanks all!

make sure to accept his answer
Justin Giboney