سؤال

I'm wondering how to format this query. I have a table with three dates, where some can be nulls. The three fields are createdDate, downDate, and fixDate. I need to query and get the latest entry depending on the date. Ex, if fixDate is not null, then it orders by the fixDate, if it is null then I need to order by downDate. If downDate is null, then I order by createdDate.

Via mySQL, I get the correct results using:

SELECT * FROM history WHERE equipment_id=88 ORDER BY IF(ISNULL(fix_date), IF(ISNULL(down_date), created_date, down_date), fix_date) DESC;

I am trying to put this into my grails project and using HQL and tried (also tried other variations of this):

History.executeQuery("SELECT FROM History WHERE equipment=:eqpt ORDER BY " +
"IF(ISNULL(fixDate), IF(ISNULL(downDate), createdDate, downDate), fixDate) DESC", [eqpt:equipment])

Also tried:

   History.executeQuery("SELECT FROM History WHERE equipment=:eqpt ORDER BY " +
    "IF(COALESCE(fixDate,downDate,createdDate) DESC", [eqpt:equipment])

ERROR I get is:

nexpected token: FROM near line 1, column 8 [SELECT FROM com...History WHERE equipment=:eqpt ORDER BY IF(COALESCE(fixDate, downDate, createdDate) DESC]

I appreciate any help, if there is a createCriteria solution as well that would be fine. Thanks.

هل كانت مفيدة؟

المحلول

I've never tried it, but the Hibernate documentation says that coalesce() is supported in the 'where' clause. If it is also available in the 'select' clause, you could select the coalesced date, and then order by it, as the documentation also states that

"The list returned by a query can be ordered by any property of a returned class or components"

So, perhaps something like:

 select h.prop1, h.prop2, coalesce(h.fixDate, h.downDate, h.createdDate) as orderDate from history h where ..... order by orderDate
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top