【问题标题】:How to do a Union SQL statement in HQL?如何在 HQL 中做 Union SQL 语句?
【发布时间】:2011-11-03 04:33:36
【问题描述】:

我正在尝试使用 HQL(休眠查询语言)在两个表之间创建联合。此 SQL 脚本在我的 SQL 服务器上运行良好:

SELECT COUNT(DISTINCT linkedin_id) as test, school_name
FROM
(SELECT * FROM alum_education 
 UNION
 SELECT * FROM alum_connection_educations) AS UNIONS where school_name='some string'

问题是,当我尝试像这样在 grails 中运行它时:

     def countOfEdu = AlumEducation.executeQuery("select count (distinct linkedinId ) as countOfEdu, schoolName as SchoolName from (SELECT * FROM alumEducation UNION SELECT * FROM alumConnectionEducations) AS UNIONS where schoolName='some string'" )

我得到这个错误:

  org.hibernate.hql.ast.QuerySyntaxException: unexpected token: ( near line 1, column 83 [select count(distinct linkedinId )  as countOfEdu, schoolName as SchoolName  from (SELECT * FROM alumEducation UNION SELECT * FROM alumConnectionEducations) AS UNIONS where schoolName='Duquesne University']

如何在 grails 中运行上述 SQL 语句?

谢谢 杰森

【问题讨论】:

标签: hibernate grails hql grails-controller


【解决方案1】:

HQL 不支持联合。 Hibernate 的 JIRA 中有一个 issue,自 2005 年起开放。

【讨论】:

  • 但是被“HHH-3971 Using UNION ALL , INTERSECTION function in hibernate”复制,并且被关闭了
【解决方案2】:

我想分享一种我发现的避免这种情况的方法。这里唯一的规则是具有相同的类型,在本例中为 String,对应于返回列表的类型,您可以添加任意数量的表:

public List<String> findByCPForCNPJ(String query){
TypedQuery<String> ccpf = manager.createQuery("select cpf from PessoaFisica where cpf like :pCpf", String.class);
ccpf.setParameter("pCpf", "%" + query + "%");
List<String> lista1 = ccpf.getResultList();

TypedQuery<String> ccnpj = manager.createQuery("select cnpj from PessoaJuridica where cnpj like :pCnpj", String.class);
ccnpj.setParameter("pCnpj", "%" + query + "%");

lista1.addAll(ccnpj.getResultList());
return lista1;
}

我在 JAVA 中使用了一种方法来解决这个问题。 我希望我贡献了一点,祝大家好运...

【讨论】:

    【解决方案3】:

    在您的情况下,真正的问题是 EJBQL 的 FROM 子句不支持子查询。

    【讨论】:

      猜你喜欢
      • 2013-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多