[英]MySQL sum() with condition in jOOQ
MySQL will allow me to pass a condition as a parameter to SUM(). MySQL将允许我将条件作为参数传递给SUM()。
SELECT COUNT(*), SUM(value > 100) FROM TABLE1;
As seen in this answer . 从这个答案中可以看出。
How do I do this in JOOQ? 我如何在JOOQ中做到这一点?
Currently (as of jOOQ 3.4), the DSL.sum()
function takes a Field<? extends Number>
当前(从jOOQ 3.4开始),
DSL.sum()
函数采用Field<? extends Number>
Field<? extends Number>
argument, so what you want to do needs some tweaking on types. Field<? extends Number>
参数,因此您需要对类型进行一些调整。 Here are two alternative ways to implement that query: 这是实现该查询的两种替代方法:
// Static imports are assumed to be present:
import static org.jooq.impl.DSL.*;
DSLContext ctx = using(configuration);
// Solution 1) Coerce Field<Boolean> to Field<Number>
ctx.select(count(), sum(field(TABLE1.VALUE.gt(100)).coerce(Integer.class)))
.from(TABLE1)
.fetch();
// Solution 2) Resort to a raw type cast
ctx.select(count(), sum((Field) field(TABLE1.VALUE.gt(100))))
.from(TABLE1)
.fetch();
In both solutions, you will need to transform an org.jooq.Condition
into an org.jooq.Field
by calling DSL.field(Condition)
. 在这两种解决方案中,您都需要通过调用
DSL.field(Condition)
将org.jooq.Condition
转换为org.jooq.Field
。 This has no effect on the generated SQL when using MySQL which natively supports this kind of usage for boolean types. 使用MySQL本机支持布尔类型的这种用法时,这对生成的SQL没有影响。 If you were using a database without support for boolean types,
DSL.field(Condition)
would generate a CASE
expression. 如果使用的数据库不支持布尔类型,则
DSL.field(Condition)
将生成一个CASE
表达式。
In jOOQ 4.0 ( Issue #3415 ), the DSL.sum()
function is scheduled to relax argument type constraints so that the call to coerce()
or the cast to (Field)
are no longer needed. 在jOOQ 4.0( 第3415版 )中,安排了
DSL.sum()
函数以放宽参数类型约束,以便不再需要调用coerce()
或coerce()
为(Field)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.