Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails GORM to return random rows from table?

In my grails application I have:

keywords = Keyword
    .findAll("from Keyword where locale = '$locale' order by rand() ", [max:20])

Assume there are thousands of rows in the table that match the above criteria. But it seems the rows that are returned from the table are not random but in the order the rows are stored in Db although within the context of 20 rows that are returned they are random. For my application to work I want this query to return completely random rows from the table like it could be row id 203 , row id 3789, row id 9087, row id 789, and so on. How is that possible?

like image 652
Alan McCloud Avatar asked Dec 07 '10 08:12

Alan McCloud


2 Answers

I use the following style:

Keyword.executeQuery('from Keyword order by rand()', [max: 9])

and it returns random rows from the entire table (we're using MySQL).

I'm not sure why execute query would behave differently from findAll though.

like image 158
leebutts Avatar answered Nov 11 '22 20:11

leebutts


If you want to use a .withCriteria you can do that workaround:

User.withCriteria {
    eq 'name', 'joseph'
    sqlRestriction " order by rand()"
}

It's important to say that sometimes ( depends on the Criteria query created ) it's necessary to add a 1=1 in sqlRestriction because it adds an "and" condition in generated query.

So if you have a sqle exception use:

sqlRestriction " 1=1 order by rand()"
like image 2
Giuseppe Iacobucci Avatar answered Nov 11 '22 20:11

Giuseppe Iacobucci