grails - 如何在grails中使用左连接?

标签 grails grails-orm

我有以下查询,当我在 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/

相关文章:

grails - Grails 2.5.0-在全新的Grails安装上设置JQGrid

go - 何时是使用 GORM 运行 Automigrate 的最佳时机

grails:按嵌套属性排序

plugins - Grails:如何引用位于已安装插件中的资源?

grails - 在Grails中解析多部分

google-app-engine - 使用App Engine插件遵循Grails脚手架教程时,list.gsp FileNotFoundException

java - 如何移动列表条目并同时更新所有条目的索引?

hibernate - grails (GORM)/hibernate 中的多对多链接表

postgresql - Grails 3.3.0 与 PostgreSQL 10.1 给出列 this_.id 不存在错误

hibernate - Grails JMS消息无法持久保存数据