使用grails和gorm执行嵌套选择

时间:2013-11-22 15:39:14

标签: sql grails gorm criteria detachedcriteria

我有以下SQL查询,我想知道是否可以使用grails在GORM样式中重写它,可能使用条件,在哪里或其他编程风格查询HQL。

SELECT count(USERID) as Result FROM Answer
WHERE USERID IN
      (SELECT USERID FROM Answer
       WHERE USERID IN (SELECT USERID FROM Answer
             WHERE USERID IN (SELECT USERID FROM Answer WHERE QID=1 AND ATxt='30') AND 
       QID=2 AND ATxt='M') AND QID=3 AND ATxt='6') AND QID=4 AND ATxt='160'

1 个答案:

答案 0 :(得分:0)

您可以使用or而不是使用嵌套的。在不知道你的域类的情况下,我假设你有类似的东西:

class User {
}

class Question {
}

class Answer {
  static belongsTo = [user: User, question: Question]
}


def question2 = Question.findById(2)
def question3 = Question.findById(3)
def question4 = Question.findById(4)

Answer.withCriteria {
  projections {
    count('user')
  }
  or {
    and {
      eq('question', question2)
      eq('aTxt', 'M')
    }
    and {
      eq('question', question3)
      eq('aTxt', '6')
    }
    and {
      eq('question', question4)
      eq('aTxt', '160')
    }
  }
}