问题
I asked a related question a week ago, but here's another problem I'm facing. I feel like such a noob, but I guess it's better to ask and learn than never learn.
Here are my three tables:
Fighters Table
fighter_id, name
Events Table
event_id, event_name, event_date
Fights Table
fight_id, fighter_a, fighter_b, winner, method, event
So in the fights table, fighter_a, fighter_b, and winner are integers that correspond to fighter_id in the Fighters table.
I'm basically on a page retrieving data based on fighter_id.
I'm trying to create rows with each fight of that fighter that includes his opponent's name, result (win, loss, draw, or nc), method, event_name, and event_date. If it's a Draw or No Contest, it'll say Draw or No Contest in Method column, while winner will be NULL.
I was looking at these MySQL IF statements, and created what would be the appropriate criteria for determining whether a fighter won, lost, got a draw, or no contest. It doesn't seem like these statements can be used in a PHP mysql_query, but at least it gives you an idea of criteria. I know I have to inner join these 3 tables together, but I'm not sure how to determine winner/loser/etc... because fighter_a or fighter_b can be a winner, or neither could be. I don't know how to approach these IF statements in MySQL query.
IF winner IS NOT NULL AND winner=fighter_id THEN SET record='win';
ELSEIF winner IS NOT NULL AND winner<>fighter_id THEN SET record='loss';
ELSEIF winner IS NULL AND method='Draw' THEN SET record='draw';
ELSEIF winner IS NULL AND method='No Contest' THEN SET record='no contest';
ELSE SET record='';
ELSE IF;
I'm trying to get a result in a table that look something like this: http://en.wikipedia.org/wiki/Fedor_Emelianenko#Mixed_martial_arts_record
回答1:
If I understand you correctly, I believe you would want to use a CASE statement to determine the result. The fighters will require a join, similar to this:
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
来源:https://stackoverflow.com/questions/10989796/more-complex-if-statements-within-mysql-query