【问题标题】:HQL Inner join on same tableHQL 内连接在同一张表上
【发布时间】:2013-01-07 13:46:11
【问题描述】:

我今天早些时候问了一个关于 GORM 的问题:How to fetch records in grails by max date and group at same time 但是,有人建议使用 HQL 可以轻松实现。但是使用 HQL 我得到unexpected token 错误。当我对此进行研究时,我发现 HQL 不允许 INNER JOINS,除非两个实体之间存在关联:HQL, left join on the same table

所以,我迷路了。首先,我很沮丧为什么 GORM 不支持这样一个简单的查询,现在有了 HQL,我的问题是:如何在子集上执行 INNER JOIN?

我尝试过的:

意外标记:(在第 1 行附近,第 16 列 [select c from (select name, max(dateCreated) as maxTime from com.mine.Color 按名称分组) as t inner join Color c on c.name = t.name and c.dateCreated = t.maxTime ]

我怀疑没有检测到Color 的第二个实例,因为包名称没有自动添加到它的前缀。所以阅读我尝试过的其他答案:

意外标记:(在第 1 行附近,第 16 列 [select c from (select name, max(dateCreated) as maxTime from com.mine.Color 按名称分组)作为 t,com.mine.Color 作为 c 在 c.name = t.name 和 c.dateCreated = t.maxTime ]

【问题讨论】:

  • 我想我有东西要给你,等一下

标签: hibernate grails hql grails-orm


【解决方案1】:

给你:

Color.executeQuery("""    
    Select c
    From Color c
    where c.dateCreated = (select max(b.dateCreated) from Color b where b.name = c.name)
    """)

【讨论】:

  • 这行得通! - 你能解释一下有什么不同吗?除了将子查询放在 where 子句中而不是 from 中?从 HQL 的角度来看,使这两个查询不同的根本原因是什么。
  • 你的查询返回记录,而我的只返回一个值,所以 HQL 可能更好地处理它。我不太确定