这是昨天这个问题的延续。
这是我的三个表:
战斗机表
fighter_id | name
-----------------------
1 | John
2 | Steve
3 | Bill
4 | Bobby
事件表
event_id | event_name | event_date
-------------------------------------------
1 | MMA | 01/01/2010
2 | Cool | 02/20/2010
3 | Yeaa! | 04/15/2010
战斗表
fight_id | fighter_a | fighter_b | winner | method | event
-----------------------------------------------------------------------
1 | 1 | 2 | 1 | Sub | 1
2 | 4 | 1 | 4 | KO | 2
3 | 1 | 3 | NULL | Draw | 3
结果试图得到
result | opponent | method | event | date
----------------------------------------------------------
Draw | Bill | Draw | Yeaa! | 04/15/2010
Loss | Bobby | KO | Cool | 02/20/2010
Win | Steve | Sub | MMA | 01/01/2010
所以在fights 表中,fighter_a、fighter_b 和winner 是对应于Fighters 表中的fighter_id 的整数。
我基本上是在基于 fighter_id ($fighter_id) 检索数据的页面上。
我正在尝试为该战斗机的每次战斗创建行,其中包括他的对手的名字、结果(赢、输、平或 nc)、方法、event_name 和 event_date。挑战在于获胜者可以在 fighter_a 或 fighter_b 中。它并不总是在同一列中。我很感激我能得到的任何帮助。
select
fight_id,
CASE
WHEN winner is not null and winner=fighter_id then 'win'
WHEN winner is not null and winner<>fighter_id then 'loss'
WHEN winner is null and method='Draw' then 'draw'
WHEN winner is null and method = 'No Contest' then 'no contest'
ELSE ''
END as match_result,
participant.name 'participant',
opponent.name 'opponent'
FROM fights
INNER JOIN fighters as participant on participant.fighter_id = fights.fighter_a
INNER JOIN fighters as oppoent on opponent.fighter_id = fights.fighter_b
WHERE
fighter_a=$fighter_id OR fighter_b=$fighter_id
ORDER BY
event_date DESC