【问题标题】:Ordering in SQL while using logical operators使用逻辑运算符在 SQL 中排序
【发布时间】:2017-06-16 09:28:56
【问题描述】:

我正在尝试编写具有 "OR" 运算符的 SQL 查询。问题是我希望它与一些人一起工作,比如说“优先事项”。我有一个实体 Item,它有两个我在搜索中使用的字段:

  • 说明
  • 标题

还有一个SQL查询:

select * from item
where description like '%a%' or title like '%a%';

我在这里想要的是,如果我们返回两个实体,其中一个根据描述匹配“%a%”,另一个根据标题匹配,则通过标题匹配的实体应该是列表中的第一个。换句话说,它应该具有更大的优先级。有没有办法可以在 SQL 中描述这样的目的?

方言:Oracle / H2

【问题讨论】:

    标签: sql oracle h2 sql-like


    【解决方案1】:

    在 Oracle 中,您可以使用 CASE 按值排序,使行按照符合您的条件的方式排序:

    /* test case */
    with item(title, description) as (
        select '__x__', '__x__' from dual union all
        select '__x__', '__a__' from dual union all
        select '__a__', '__x__' from dual union all
        select '__a__', '__a__' from dual
        )
    /* the query */
    select *
    from item
    where description like '%a%' or title like '%a%'
    order by case
              when title like '%a%'
                then 1
              else 2
             end
    

    这给出了:

    TITLE DESCR
    ----- -----
    __a__ __x__
    __a__ __a__
    __x__ __a__
    

    【讨论】:

    • 谢谢!这对我来说非常有效!我使用 jpa2 标准。 Expression orderByExp = criteriaBuilder.selectCase() .when(predicate, 1).otherwise(2); query.orderBy(criteriaBuilder.asc(orderByExp));
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    相关资源
    最近更新 更多