MySQL查询WHERE包括CASE还是IF?

时间:2010-04-15 08:35:39

标签: mysql case where

奇怪的问题。

我的查询看起来像

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

显然MySQL返回错误的rowcount,我认为我的问题出在WHERE ... CASE语句的逻辑中。也许用括号?也许我应该选择运营商OR而不是AND?我的第二个WHEN是否也包括括号,即使我只比较一个字段?我应该使用IF而不是CASE吗?

基本上我想要排除某些具有特定值的行,如果字段foobar

中的特定值

我会全力以赴,但完成该查询需要花费大量时间...... :(

编辑:对于笔记,我的问题是,我忘记了ELSE中的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

此解决方案也有效,但发布的更好......

1 个答案:

答案 0 :(得分:6)

你应该在这里使用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)