Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Daniel1836's avatar

How can use an IF/ELSE statement in my SQL query?

SELECT sum(home_score) as C FROM u_games WHERE (home_team_id ='$team_id' OR away_team_id = '$team_id')

I need to run one query if $team_id = home_team_id and a different one if $team_id = away_team_id

I'm trying to get the total score of a team. But I don't know beforehand whether it's home or away. It's random.

Thanks

0 likes
4 replies
MichalOravec's avatar
$score = DB::table('u_games')
    ->where('home_team_id', $team_id)
    ->orWhere('away_team_id', $team_id)
    ->sum('home_score');
Daniel1836's avatar

I'm using vanilla PHP (no framework). Also if $team_id = away_team_id I need away_score column not home_score.

tykus's avatar
tykus
Best Answer
Level 104

You should be able to achieve what you need using a CASE statement, e.g.

select sum(
	case
		when away_team_id = :team_id then away_score
		when home_team_id = :team_id then home_score
	end
) as C
from u_games
where (away_team_id = :team_id or home_team_id = :team_id)

Please or to participate in this conversation.