【问题标题】:When using an OR operator, will the query return left condition over the right?使用 OR 运算符时,查询是否会在右侧返回左侧条件?
【发布时间】:2020-04-29 16:45:37
【问题描述】:

我想返回 单个 行,但需要一个查询来限定这两个条件。

例如

SELECT * FROM user WHERE admin < 10 OR admin > 100 LIMIT 1

当我查询这个时,它会返回它找到的第一行的管理值小于 10 吗?如果没有,我将如何实现?

【问题讨论】:

  • 请提供样本数据和期望的结果。这将返回与where 子句匹配的第一行。如果您想要匹配admin &lt; 10 的第一行,则删除or amin &gt; 100。
  • 我想找到具有admin &lt; 10 的第一行,但如果没有具有该值的行,那么我想返回具有admin &gt; 100 的第一行。我认为示例查询很简单,可以提供答案,示例数据会使事情变得混乱。

标签: sql operators where-clause operator-keyword


【解决方案1】:

您可以使用order by 执行此操作。我建议:

SELECT *
FROM user
WHERE admin < 10 OR admin > 100
ORDER BY admin
LIMIT 1

【讨论】:

    【解决方案2】:

    来自cmets:

    我想找到 admin 100 的第一行

    一个选项使用union all 和not exists:

    (select * from users where admin < 10 limit 1)
    union all
    (
        select * 
        from users 
        where 
            admin > 100 
            and not exists (select 1 from users where admin < 10)
        limit 1
    )
    

    另一种解决方案是进行条件排序:

    select *
    from users 
    where admin < 10 and admin > 100
    order by case when admin < 10 then 1 else 2 end
    limit 1
    

    请注意,如果您要向其中添加order by 子句,您的查询会更有意义。在不使用 order by 的情况下使用 limit 会导致从满足谓词的行中返回 abritrary 行。

    【讨论】:

    • 使用UNION ALL时,你这里写的查询不会返回2行吗?
    • @Xylum:第二个子查询只有在第一个子查询没有返回的情况下才会返回(这就是not exists 的目的)。
    猜你喜欢
    • 2023-03-07
    • 2020-06-26
    • 2016-06-23
    • 2016-06-08
    • 2013-12-07
    相关资源
    最近更新 更多