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(
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<YearToMonth>
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 <T extends java.util.Date>
Field<T> dateInCurrentYear(Field<T> 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.
One way of solving the issue is using a String in the where clause. I'm writing it down here for completeness, but I think it misses the point of jOOQ
context.
selectCount().
from(PEOPLE).
where("DATE_ADD(people_dob, INTERVAL YEAR(CURDATE()) - YEAR(people_dob) YEAR)" +
" BETWEEN DATE_SUB(CURDATE(), INTERVAL 7 DAY) AND CURDATE()").