hql不能在distinct,group by结果集上使用count的问题,报语法错误

hql有如下两个限制:

HQL(SQL)不支持select count(distinct x, y) from xx;

HQL不支持select count(*) from (select distinct x, y from xx);

即:HQL不支持from语句中的子查询。


PS:hql不能在distinct,group by结果集上使用count的问题 !


可以把对hql的查询直接转换成堆sql的操作:

<pre name="code" class="java">String sql = "select count(distinct(order_id)) from t_credit_log where usercode = :usercode and remark like '%"
		+ remark + "%'";
Query query = ht.getSessionFactory().openSession().createSQLQuery(sql)
				.setParameter("usercode", usercode);
	List list = query.list();
	BigDecimal count = list == null || list.size() <= 0 ? new BigDecimal(0)
	: (BigDecimal) list.get(0);
	if (count.intValue() >= 3) {
	flag = true;
	}


 

由于我返回的数据不大,所以直接通过返回一个集合之后取大小也能解决问题,但是结果集大就有效率问题了。


注意:转换成对sql的查询,count返回的结果类型是java.math.BigDecimal,所以如果直接对最后的结果要处理下,转成int类型的。


在网上找的方法,把hql语句转换成sql:

public Long getDataTotal(String hql, Object[] values) { 

QueryTranslatorImpl queryTranslator = new QueryTranslatorImpl(hql, hql, 
Collections.EMPTY_MAP, (SessionFactoryImplementor) this 
.getSessionFactory()); 
queryTranslator.compile(Collections.EMPTY_MAP, false); 
String tempSQL = queryTranslator.getSQLString(); 
String countSQL = "select count(*) from (" + tempSQL + ") tmp_count_t"; 
Query query = this.getSession().createSQLQuery(countSQL); 
for (int i = 0; i < values.length; i++) { 
query.setParameter(i, values[i]); 
} 
List list = query.list(); 
BigDecimal count = list == null || list.size() <= 0 ? new BigDecimal(0) 
: (BigDecimal) list.get(0); 
return count.longValue(); 
} 
个人感觉有点麻烦,还不如直接写sql执行。



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值