【问题标题】:Unable to run CASE WHEN for array in Spring Boot repository无法为 Spring Boot 存储库中的数组运行 CASE WHEN
【发布时间】:2021-03-30 02:20:36
【问题描述】:

我正在尝试运行它

@Query(value = "SELECT t.*\n" +
            "FROM tlm_trade t\n" +
            "left join tlm_trade_nugget n\n" +
            "on t.trade_nugget_id=n.id\n" +
            "where \n" +
            "(year(t.created_date) in (case when ?1 is null then year(t.created_date) else ?1 end))\n" +
            ";", nativeQuery = true)
    List<TlmTrade> findByFilter(Set<Integer> year);
;

当我将它作为参数传递时


[2021,2020,2019]

得到了这个错误

SQLException:操作数应包含 1 列

知道有什么问题吗?

【问题讨论】:

    标签: sql spring-boot jpa


    【解决方案1】:

    case when ... endexpression,它们评估为单个值

    在您的示例中,您希望可以使用 case expression 充当“动态 sql”。即如果 ?1 为空,则插入术语“year(t.created_date)”,但如果 ?1 不为空,则插入 ?1

    你不能这样做。

    在形成@Query 之前进行分支会更有意义,一个分支为 ?1 为空,另一个分支使用 ?1

    另外,在 where 子句中避免 case 表达式,最好用二进制术语表达过滤器,例如,在需要的地方使用括号:

    "where (?1 IS NULL AND year(t.created_date) = '2021' )\n"
    

    ?1 顺便说一下,需要等于某个值,或者大于某个值等等。?1 本身不会形成过滤条件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-25
      • 2011-05-19
      • 2017-03-28
      • 1970-01-01
      • 1970-01-01
      • 2021-11-07
      • 2017-12-03
      • 1970-01-01
      相关资源
      最近更新 更多