开发者

MySQL Query WHERE Including CASE or IF?

Strange problem.

My Query 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 a wrong rowcount and I think my problem is in the logic of the WHERE ... CASE statement. Maybe with the brackets? Maybe I should go for operator OR and not AND? Should my the second WHEN include brackets also, even when I only compare one field? Should I use IF and not CASE?

Basically I want to exclude some rows with specific values IF theres a specific value in field foo or bar

I would try that all out, but it takes a huge amount of time 开发者_如何转开发to complete that query... :(

Edit: Just for the notes, my problem was, that I forgot the ELSE in my 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

This solution works also, but the posted one is better...


You should use OR here instead of 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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜