Finding upcoming birthdays with jOOQ

前端 未结 2 1237
萌比男神i
萌比男神i 2021-01-22 04:17

I\'m trying to convert an existing query which looks for upcoming birthdays to use jOOQ. My original query - using MySQL, and a bit simplified - is

SELECT COUNT(         


        
2条回答
  •  心在旅途
    2021-01-22 04:39

    jOOQ's Field.add() method is inspired by Oracle's interpretation of

    DATE + NUMBER
    

    ... where NUMBER (if an Integer or Double) is a number of days. What you want is the equivalent of adding a SQL standard INTERVAL YEAR TO MONTH to a given date. This could be achieved through using jOOQ's YearToMonth interval type, if you wanted to add a constant interval. The YearToMonth type also extends java.lang.Number, and can thus also be used with Field.add(), intuitively.

    While it might be possible to generate such a Field through existing jOOQ 3.2 API, I believe that you will be better off to just resort to plain SQL, possibly by creating a reusable method:

    public static  
    Field dateInCurrentYear(Field field) {
        return DSL.field("DATE_ADD({0}, INTERVAL YEAR(CURDATE()) - YEAR({0}) YEAR)",
                         field.getDataType(),
                         field);
    }
    

    This might be a useful feature addition for #2727 as well...

    Unfortunately, the various SQL dialects' interpretations of date time arithmetic is hard to standardise. We're constantly improving things there, but often, plain SQL is the best way to write dialect-specific date time arithmetic expressions.

提交回复
热议问题