简体   繁体   中英

Grails createCriteria mysql IF statement

I'm a newbie in Grails, and I have a big problem. I have this domain:

class Product{

  String name
  Integer priority
  Double quantity
}

I want to sort Products by priority (which IS 0 or 1) - desc, and then sort by quantity. In mysql I do it like this:

select name, IF(quantity>=1,1,0) as q from product
where ...
order by priority desc, q desc, id desc

There is alse CASE statement in mysql, but in Grails I don't have an idea how to create criteria for this.

Thanks in advance!

Product.createCriteria().list(){
    projection{   // 1. because you only want to getname list.
       property("name")
    }
    ge("quantity", 1) // 2. greater than or equal 1

   order("priority", "desc" ) // by default "asc"
   order("quantity", "desc" )
   order("id", "desc" )
};
  1. Only Returns the given property in the returned results when you wrapping by "projections".

     projections { property("firstName") }
  2. Where a property is greater than or equal to a particular.

     ge("balance", 1000)
  3. "desc" or "asc" for descending and ascending respectively. By default, results are sorted in ascending order

Grails Official Doc v4.0.0

One needs to create a custom Order (sql-generating) class to sort on arbitrary expression, or just go with SQL.

Looks like even HQL cannot do that: Product.executeQuery('from Product p order by (id > 100)') fails for me with HQL syntax error.

Try to do something around below :

  select name,IF(quantity>=1,1,0) as q
  from product 
  where ... 
  order by IF(priority=1,0,1), q desc, id desc

Considering Priority 1= high 0=low

Please do required changes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM