GORM distinct() + count() 的问题

14 篇文章 0 订阅

当我们想要查询 “不同记录的条数” 时,我们可能会这样写:

int totalCampaignUser = CampaignParticipation.where {
    eq "campaign.id", campaignToJoin.id
}.distinct("user").count()?.intValue() ?: 0

但这样会生成一个错误的 SQL

select distinct this_.user_id as y0_, count(*) as y1_ from campaign_participation this_ where this_.campaign_id=? limit ?

原因是用了聚合函数count(*),但 select 子句中的字段"user_id"没有出现在 group by 中。

报错信息:

2020-04-30 13:28:00.351 DEBUG --- [    Test worker] org.hibernate.SQL                        : select distinct this_.user_id as y0_, count(*) as y1_ from campaign_participation this_ where this_.campaign_id=? limit ?
2020-04-30 13:28:00.351 TRACE --- [    Test worker] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [BIGINT] - [188]
2020-04-30 13:28:00.446 ERROR --- [    Test worker] o.h.engine.jdbc.spi.SqlExceptionHelper   : In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'chess_test.this_.user_id'; this is incompatible with sql_mode=only_full_group_by

解决办法:

可以用 countDistinct(),例如这样:

def c = Account.createCriteria()
def numberOfBranches = c.get {
    projections {
        countDistinct('branch')
    }
}

具体项目中,试验成功的代码:

Number totalCampaignUser = CampaignParticipation.where {
    eq "campaign.id", campaignToJoin.id
    projections {
        countDistinct "user"
    }
}.get() as Number ?: 0
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值