我正在为体育游戏创建一个数据库。
我有一个名为游戏的表:
-----------------------------
winner | team_id1 | team_id2
-----------------------------
我有一个表团队
----------
id | title
----------
如果winner = 1
,team_id1
是获胜者团队的id
如果winner = 2
,team_id2
是获胜者团队的id
最后,我希望每场比赛都获得冠军队的头衔,然后是失败者队的头衔。
尝试了类似的事情:
select tea1.title, tea2.title
from games gam
join teams tea1 on case
when gam.winner = 1 and gam.team1_id = tea1.id then 1
when gam.winner = 2 and gam.team2_id = tea1.id then 1
else 0
end = 1
join teams tea2 on case
when gam.winner = 2 and gam.team1_id = tea2.id then 1
when gam.winner = 1 and gam.team2_id = tea2.id then 1
else 0
end = 1
但请求挂起,我不明白为什么。
答案 0 :(得分:2)
尝试在select子句而不是连接条件中获得赢家或输家。
select
gam.winner,
case when gam.winner=1 then t1.title else t2.title end as winner_title,
case when gam.winner=2 then t1.title else t2.title end as loser_title
from
games gam
left join
teams t1
on
gam.team1_id = t1.id
left join
teams t2
on
gam.team2_id = t2.id