2012-09-11 26 views
0

我不知道這個查詢是否可以使用grails executeQuery。我做樣本域類:grails hibernateQuery count

class Child { 
    String firstName 
    String lastName 
    String nickName 
} 

這裏是我舉:

class BootStrap { 

def init = { servletContext -> 

    def childOne = new Child(firstName: 'Poliwag', lastName:'Wrath', nickName: 'taurus') 
    def childTwo = new Child(firstName: 'Poliwarp', lastName: 'Wrath', nickName:'libra') 
    def childThree = new Child(firstName: 'Poliwag', lastName: 'Wrath',nickName:'aries') 
    def childFour = new Child(firstName: 'Poliwag', lastName: 'Wrath',nickName:'virgo') 

    childOne.save(flush: true, failOnError: true) 
    childTwo.save(flush: true, failOnError: true) 
    childThree.save(flush: true, failOnError: true) 
    childFour.save(flush: true, failOnError: true)   
    } 

} 

當你看到,我有兩個具有相同的firstName & 的lastName財產2個樣本數據條目,他們僅在nickName屬性上有所不同。我理想中的executeQuery獲得是項的列表,它的的firstName & lastName的特性是從其他2項相同。是否有可能在grails中使用count(...)運算符executeQuery?我覺得這就是這個使用動態查找器的等效代碼:

def list = [] 
def c = Child.countByFirstNameAndLastName('Poliwag',Wrath) 
if (c == 2) { 
    list.add(Child.findByFirstNameAndLastName('Poliwag','Wrath')) 
} 

我想如果可能的話我用的executeQuery這將節省更多的代碼。 謝謝..

回答

2

如果暱稱和姓氏在您的示例中是固定值,那麼您可以在executeQuery中使用常規的WHERE條件和SELECT COUNT,這與您使用的countBy方法相同。

但是,如果這些值不固定,您可以使用GROUP BY和HAVING來完成此操作。通過做一些

c.each{ 
    println it.firstname + " " + it.lastname 
} 
+0

感謝您的信息,只是有一個跟進的問題。 我做的是這樣的: def c = Child.executeQuery(「通過c.firstName選擇新的地圖(c.firstName作爲名字,c.lastName作爲姓氏)從c兒童c組,c.firstName具有count(c.firstName )= 3和計數(c.lastName)= 4「) 它只返回一個_null_列表,我期望它會返回具有相同的名字與另外2個條目,並具有相同的姓氏與另外3個條目。 – antibry

+0

GROUP BY語句的工作方式是它會創建具有您指定的列的組,並且該HAVING語句將在GROUP BY返回的集合上運行。因此,不要寫'有count(c.firstname = 2),我也可以寫count(c.lastname)= 2,我會得到相同的結果。如果我不清楚,你可以看看這個例子來更好地理解它:http://www.plus2net.com/sql_tutorial/sql_group_by2.php – MBozic

1

可以實現它:但是這樣你不能返回整個對象,只有你是分組的屬性:

def c = Child.executeQuery("select new map(c.firstname as firstname, c.lastname as lastname) from Child c group by c.firstname, c.lastname having count(c.firstname) = 2") 

你可以通過結果地圖像這樣的迭代像這樣的事情。

def x = Child.executeQuery("select c1 from Child c1,Child c2 where c1.firstName=c2.firstName and c1.nickName<>c2.nickName") 

println x.size() 
0
def x = Child.executeQuery("select count (*) from Child c1,Child c2 where c1.firstName=c2.firstName and c1.nickName<>c2.nickName") 

println x[0]