如何在grails中使用左连接?

How to use left join in grails?

我有以下查询,它在 mysql 中获取正确的结果,当我在 grails 中编写相同的查询时,它抛出错误 "Path expected for join"

select u.username,u.transactioncode,count(distinct t.rolename) roles
from user u 
left join transaction t on u.transactioncode=t.transactioncode 
group by u.username, u.transactioncode; 

How to change the query?

Modifying the query to make it work in grails

function(int id)
 {
   def sql = new Sql(dataSource)
        def output = sql.rows("select 
        u.username,u.transactioncode,count(distinct t.rolename) roles from 
        user u left join transaction t on 
        u.transactioncode=t.transactioncode where u.userid=:id group by 
        u.username, u.transactioncode")
       sql.close();
 }

 It throws an error in the where condition You have an error in your SQL 
 syntax; check the manual that corresponds to your MySQL server version for 
 the right syntax to use near ':id.

我认为最简单的方法是使用 Groovy SQL。为此,您应该将 dataSource 注入您的服务或控制器:

import javax.sql.DataSource

DataSource dataSource

然后像

一样执行查询
new Sql(dataSource).rows(q)

其中 q 将是您的确切查询。

Here 是将 Groovy SQL 与 Grails 一起使用的好教程。


我什至不知道是否可以在内联 HQL 中使用左连接 - 而这正是 executeQuery 应该使用的。 Criterias,如@JMa 所述,将是一个有效选项,但我认为它们通常用于查询域对象,并且您需要自定义结果集。 This 是关于何时在 Grails 中使用不同类型的查询选项的另一个很好的解释。