This is the first time I've created a SQL with CASE
. I must have done something wrong with WHEN
and ELSE
.
I would like to obtain the condition that:
If
team_away
....is contained in theround
column which has1
...and ifteam_away
is contained in theteam_away
column....then it is OKIf
team_away
....is contained in theround
column which has1
...and ifteam_away
is contained in theteam_home
column....then it is NULL
Notice that team_away=?
is both a variable and the column name
What am I doing wrong?
SELECT team_home, team_away, score_home, score_away
FROM Results
WHERE
(CASE
WHEN current_round= 1 AND team_home = team_away=? THEN NULL
ELSE current_round= 1 AND team_away = team_away=?
END)
LIMIT 1;
''', [Match_Team_Away, Match_Team_Away])
Maybe the problem is in the syntax setting: AND team_away = team_away=?
or team_home = team_away=?
(two =)
UPDATE:
This is table Result:
current_round | team_home | team_away | score_home | score_away |
---|---|---|---|---|
1 | Liverpool | United | 3 | 0 |
1 | Arsenal | Aston Villa | 4 | 1 |
For example if my team_away
variable (team_away=?) is United
, it means it is in the team_away
table as you can see. In this case I would like to use the second CASE (the one with ELSE). Whereas if United
had been in the team_home
table and not in team_away
, then I would have liked to receive a NULL
team_away=?
isn't a variable or parameter name, it's an equality check betweenteam_away
and a nameless parameter?
. CASE is an expression that returns a value, not a way to group conditions. You can compare its return value to something else if you want, but that usually leads to bad performance. If you want to combine options, useOR
. The evaluation order doesn't mattercase when
in awhere
statement.case when
is used to create a new column based on some conditions.where
is used to filter. What do you want to do ? filter the lines or create something new ?If team_away....is contained in the round column which has 1...and if team_away is contained in the team_away column....then it is OK
what does that mean? One column is contained in another? But both are equal to 1? Or a column is contained in itself?