gpt4 book ai didi

MySQL 查询 WHERE 包括 CASE 还是 IF?

转载 作者:可可西里 更新时间:2023-11-01 07:57:39 24 4
gpt4 key购买 nike

奇怪的问题。

我的查询看起来像

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 返回了错误的行数,我认为我的问题出在 WHERE ... CASE 语句的逻辑上。也许用括号?也许我应该选择运算符 OR 而不是 AND?即使我只比较一个字段,我的第二个 WHEN 是否也应该包含方括号?我应该使用 IF 而不是 CASE 吗?

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

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

编辑:只是为了注释,我的问题是,我忘记了 CASE 中的 ELSE

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

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

最佳答案

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

关于MySQL 查询 WHERE 包括 CASE 还是 IF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2643783/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com