Return条两列中有一个匹配值的记录

Return records that has one matching value in two columns

我有以下 SQL table,我正在尝试根据布尔值是否为真从中检索详细信息。

虚拟数据

Name    |  Score  | Deleted  | annonomous  | showuser | ID
Jane    |   5     | 0        | 1           | 0        | 7896
John    |   1     | 1        | 1           | 0        | 7896
John    |   6     | 0        | 0           | 0        | 7896
John    |   9     | 0        | 0           | 1        | 7896

我想取回具有 annonomous=1 或 showuser=1 的特定用户的记录。注意这两列永远不能同时具有相同的 true 值(如切换)

这是我试过的

select *
from table
where name='John' and Deleted=0 and ID=7896 and annonomous=1 OR showuser=1

但是上面的查询返回了我删除的用户

这是我得到的输出

Name    |  Score  | Deleted  | annonomous  | showuser | ID  
John    |   1     | 1        | 1           | 0        | 7896  
John    |   9     | 0        | 0           | 1        | 7896

但我想要的输出是

Name    |  Score  | Deleted  | annonomous  | showuser | ID  
John    |   9     | 0        | 0           | 1        | 7896

几乎是一个错字,但您的 WHERE 子句中需要括号:

SELECT *
FROM yourTable
WHERE name = 'John' AND Deleted = 0 ID = 7896 AND (annonomous = 1 OR showuser = 1);

因为 AND 运算符比 OR 具有 更高的 优先级,您当前的查询被评估为:

SELECT *
FROM yourTable
WHERE (name = 'John' AND Deleted = 0 ID = 7896 AND annonomous = 1) OR showuser = 1;

此版本将无条件地 return 任何具有 showuser = 1 的记录,无论用户是谁。