在Criteria查询中转换SQL语句

时间:2014-09-12 08:54:52

标签: sql grails createcriteria

我需要一些帮助,以便我可以在grails条件查询中转换我的sql:

String query = """select * from personal_detail as pd
      where pd.id in (
      select u.personal_detail_id from user u where u.id in
      (
        SELECT ur.user_id FROM user_role ur where ur.role_id = '${role.id}'
     )
      and u.enabled = true and u.is_deleted = false
     )
      and
     pd.status = true 
    """

编辑:       我被困在内在的选择上,即

SELECT ur.user_id FROM user_role ur where ur.role_id = '${role.id}'

对于内部选择我试过这个:

def results = UserRole.createCriteria().list {
        createAlias('user','user')
            eq('role', role)
            eq('user.enabled',true)
            eq('user.isDeleted',false)

    }

这会产生异常

 Unknown column 'user1_.enabled' in 'where clause'. Stacktrace follows:
Message: Unknown column 'user1_.enabled' in 'where clause'
Line | Method
->>  411 | handleNewInstance  in com.mysql.jdbc.Util
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
|    386 | getInstance        in     ''
|   1052 | createSQLException in com.mysql.jdbc.SQLError
|   4096 | checkErrorPacket   in com.mysql.jdbc.MysqlIO

1 个答案:

答案 0 :(得分:1)

如果没有看到您的对象模型,很难肯定地说,但您可能正在寻找类似的东西......

def results = UserRole.withCriteria {
    eq 'role', role
    user {
        eq 'enabled', true
        eq 'isDeleted', false
    }
}

我希望有所帮助。