带括号的分组条件不起作用

Grouping conditions with parentheses not working

我正在尝试在 Postgres 中使用如下所示的 SQL 查询:

UPDATE gamebet 
SET points = 15 
WHERE game = 8 
  AND "scoreT1" > "scoreT2" 
  AND "scoreT1" - "scoreT2" != 1 
  AND ("scoreT1" != 1 AND "scoreT2" != 0)

它应该更新一些 scoreT1 大于 scoreT2 的投注的分数,但有些行不应该更新。那就是当 scoreT1 - scoreT2 = 1 并且如果 scoreT1 = 1 和 scoreT2 = 0,但它应该仅在满足这两个条件时才适用。不知何故,括号没有被应用。因为例如此记录未修改:

scoreT1 = 3
scoreT2 = 0

这条记录应该被更新,但是由于条件之一是scoreT2 != 0所以它没有被更新。我如何将需要满足的最后条件组合在一起?

根据你的描述你想要

 NOT("scoreT1" - "scoreT2" == 1 OR ("scoreT1" == 1 AND "scoreT2" == 0))

逻辑上应该是

 "scoreT1" - "scoreT2" != 1 AND ("scoreT1" != 1 OR "scoreT2" != 0)

当您将 NOT 运算符转换为复合比较时,您将 ANDs 翻转为 ORs,反之亦然。

只要不排除 NULL 值,您的描述必须翻译成这样:

UPDATE gamebet 
SET    points = 15 
WHERE  game = 8 
AND   "scoreT1" > "scoreT2" 
AND  ("scoreT1" = "scoreT2" + 1 AND "scoreT1" = 1) IS NOT TRUE;

附加条件 "scoreT2" = 0 符合前两个条件的逻辑并且是多余的。

如果"scoreT1""scoreT2"定义为NOT NULL,可以进一步简化:

...
AND   NOT ("scoreT1" = "scoreT2" + 1 AND "scoreT1" = 1)

或反逻辑:

...
AND   ("scoreT1" <> "scoreT2" + 1 OR "scoreT1" <> 1)

阅读手册中的 Logical Operators, Comparison Operators and Operator Precedence

并且如果points已经可以成为 15,那么添加另一个谓词以避免空更新是值得的:

AND points IS DISTINCT FROM 15

或者,排除 NULL 值:

AND points <> 15

详情:

  • How do I (or can I) SELECT DISTINCT on multiple columns?