我可以在hql中从多个表中添加金额

时间:2014-05-19 11:03:21

标签: java sql hibernate jpa hql

我想在HQL中执行类似于SQL的查询:

SELECT (
    SELECT COUNT(*) FROM EMPLOYER +
    SELECT COUNT(*) FROM COMPANIES
       ) 
FROM DUAL

当我向查询添加“FROM DUAL”时,我收到错误:

org.hibernate.hql.ast.QuerySyntaxException: DUAL is not mapped

如果我放弃“FROM DUAL”,我会得到:

org.hibernate.hql.ast.QuerySyntaxException: unexpected end of subtree 

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

在SQL中,子查询需要自己的一组括号,所以试试这个:

SELECT ((SELECT COUNT(*) FROM EMPLOYER) +
        (SELECT COUNT(*) FROM COMPANIES)
       ) 

如果这不起作用,请使用from条款:

SELECT e.cnt + c.cnt
FROM (SELECT COUNT(*) as cnt FROM EMPLOYER
     ) e CROSS JOIN +
     (SELECT COUNT(*) as cnt
      FROM COMPANIES
     ) c

答案 1 :(得分:1)

由于您没有加入公司和员工表,因此最好运行两个查询:

int companyCount = ((Number) getSession().createQuery("select count(*) from Company").uniqueResult()).intValue();
int employeeCount = ((Number) getSession().createQuery("select count(*) from Employee").uniqueResult()).intValue();
int totalCount = companyCount + employeeCount;

由于PostgreSQL返回BigInteger而HDSQLDB返回一个Integer,因此需要(Number),但两者都是Number的子类。