代码之家  ›  专栏  ›  技术社区  ›  deanpillow

返回两列中有一个匹配值的记录

  •  0
  • deanpillow  · 技术社区  · 2 年前

    我有下面的SQL表,我试图根据布尔值是否为true从中检索详细信息。

    虚拟数据

    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
    
    1 回复  |  直到 2 年前
        1
  •  3
  •   Tim Biegeleisen    2 年前

    几乎是一个拼写错误,但您需要在 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;
    

    此版本将无条件返回具有 showuser = 1 ,而不管用户是谁。