MySQL Query WHERE Including CASE or IF?

A strange problem.

My request looks like

SELECT DISTINCT ID, `etcetc`, `if/elses over muliple joined tables` FROM
    table1 AS `t1`
    # some joins, eventually unrelated in that context
WHERE
# some standard where statements, they work/

CASE 
    WHEN `t1`.`field` = "foo" THEN (`t1`.`anOtherField` != 123 AND `t1`.`anOtherField` != 456 AND `t1`.`anOtherOtherField` != "some String")
    WHEN `t1`.`field` = "bar" THEN `t1`.`aSecondOtherField` != 12345
    END

#ORDER BY CASE etc. Standard Stuff

Apperantly MySQL returns an invalid row row, and I think my problem is the logic of the WHERE ... CASE statement. Maybe using brackets? Maybe I should go for the operator OR, not AND? Should my second WHENinclude brackets even when I compare only one field? Should I use IF, not CASE?

Basically, I want to exclude some lines with certain values. IF has a specific value in the field fooorbar

I would try everything, but it takes a huge amount of time to complete this request ... :(

Edit: For notes only, my problem was what I forgot ELSEin mine CASE.

CASE 
    WHEN `t1`.`field` = "foo" THEN (`t1`.`anOtherField` != 123 AND `t1`.`anOtherField` != 456 AND `t1`.`anOtherOtherField` != "some String")
    WHEN `t1`.`field` = "bar" THEN (`t1`.`aSecondOtherField` != 12345)
    ELSE TRUE
END

, ...

+3
1

OR CASE:

WHERE
(`t1`.`field` = "foo" AND `t1`.`anOtherField` != 123 AND `t1`.`anOtherField` != 456 AND `t1`.`anOtherOtherField` != "some String")
OR
(`t1`.`field` = "bar" AND `t1`.`aSecondOtherField` != 12345)
+6

Source: https://habr.com/ru/post/1741236/


All Articles