【问题标题】:How to get the distinct values in a column as well as total count using spring jpa pagination如何使用spring jpa分页获取列中的不同值以及总数
【发布时间】:2022-01-03 12:57:06
【问题描述】:

我正在尝试选择 C ​​列的唯一值列表以及相应的计数。我的代码如下

    @Query(value = "SELECT DISTINCT t.C FROM table t WHERE t.param = :param order by t.C",
        countQuery = "SELECT count(DISTINCT t.C) FROM table t WHERE t.param = :param")
    Page<String> findUniqueWithCountPagination(Pageable pageable,
        @Param("param") String param);

我收到错误ORDER BY items must appear in the select list if SELECT DISTINCT is specified。当我启用 show-sql 属性时,我注意到 Spring 正在将另一列 U 自动添加到 order by 过滤器中。 U 是表 t 中的时间戳列。

如何去掉 order by 中不需要的字段 U?如果这不可能,有没有其他方法可以为我的要求编写查询?

【问题讨论】:

  • 你能粘贴你提到的生成的查询吗?
  • select distinct TOP(?) t0_.C as col_0_0_ from dbo.t t0_ where t0_.param=? order by t0_.C, to_.U desc
  • 这种查询不是更适合您的用例吗?SELECT t.C, COUNT(*) FROM t WHERE t.param = '1' GROUP BY t.C order by t.C? (这是 Oracle 语法,未经测试。仅供参考。)
  • 不,我需要使用分页,所以我需要编写两个不同的查询来获取值和计数。
  • 事后如何对结果中没有的内容进行排序?

标签: java spring spring-boot hibernate spring-data-jpa


【解决方案1】:

我只需要 C 列中的唯一值并且它是计数的,因此我对 C 本身应用了排序并将其从查询中删除。 order by 在执行期间自动应用。代码sn-ps如下:

 Pageable pageable = PageRequest.of(filterOption.getPageNo(), filterOption.getPageSize(), Sort.Direction.DESC, C);


 // repository class
 @Query(value = "SELECT DISTINCT t.C FROM table t WHERE t.param = :param",
 countQuery = "SELECT count(DISTINCT t.C) FROM table t WHERE t.param = :param")
 Page<String> findUniqueWithCountPagination(Pageable pageable,
 @Param("param") String param);

【讨论】:

    猜你喜欢
    • 2016-08-27
    • 2020-01-16
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-18
    相关资源
    最近更新 更多