一 問題
spring data jpa hql 默認的查詢總數和SQL語句返回的條數不一致,SQL語句如下:
select distinct(a.group_id) from table_a a
left join table_b b on b.id = a.goup_id
where a.state = 1
order by b.create_time desc;
其中,table_a 是明細表(流水錶),table_b 是分組表(如按日期分組);
目的是想取出table_a 中不同group_id的記錄列表,考慮到table_b 中的分組id並不一定會在table_a 中出現,所以查的table_a 表中的distinct(group_id)。
而在頁面分頁展示時,卻不是自己想要的結果,總數比展示的分組記錄數多了。發現總數是table_a 表記錄的總數。
二 解決方法
查看日誌才發現,jpa的默認查詢數據總數的語句爲:
select count(*) as count from table_a a
left join table_b b on b.id = a.goup_id
where a.state = 1
order by b.create_time desc;
這裏的count語句沒有了distinct,顯然和自己需要的分組總數不一致,這裏查的是table_a表的明細總數。
自己的解決方法是:
給查詢語句加上group by 分組,讓jpa 的默認查詢數據總數的語句帶上group by以實現一致的查詢總數。分組後的語句如下:
select distinct(a.group_id) from table_a a
left join table_b b on b.id = a.goup_id
where a.state = 1
group by a.group_id
order by b.create_time desc;
改完後,jpa的默認彙總數量語句也字段加上了group by。
最後,數據分頁展示正常。