我有以下查询,当我在 grails 中编写相同的查询时,它会在 mysql 中获取正确的结果,它会抛出错误“连接预期的路径”
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 .为此,您应该注入(inject) dataSource
进入您的服务或 Controller :
import javax.sql.DataSource
DataSource dataSource
然后像这样执行查询
new Sql(dataSource).rows(q)
在哪里
q
将是您的确切查询。Here是一个很好的使用 Groovy SQL 和 Grails 的教程。
我什至不知道是否可以在内联 HQL 中使用左连接 - 这就是应该与
executeQuery
一起使用的内容. Criterias
,正如@JMa 所提到的,将是一个有效的选项,但我认为它们通常用于查询域对象并且您需要自定义结果集。 This是关于何时在 Grails 中使用不同类型的查询选项的另一个很好的解释。
关于grails - 如何在grails中使用左连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49894201/