如何用Java中的Jooq实现多列条件的CASE WHEN语句?
用jOOQ实现指定SQL CASE逻辑
当然可以用jOOQ实现这段CASE逻辑,以下是具体实现方式:
原SQL逻辑
case when columnA = 'On' and columnB <= current_date() and columnC > current_date() then columnA else 'NoChange' end
jOOQ实现代码
假设你已经通过jOOQ代码生成器得到了对应表和字段的对象(比如MyTable类及其静态实例MY_TABLE),可以这样写:
import org.jooq.Field; import static org.jooq.impl.DSL.*; // 构造CASE表达式 Field<String> caseExpr = when( MY_TABLE.COLUMN_A.equal("On") .and(MY_TABLE.COLUMN_B.le(currentDate())) .and(MY_TABLE.COLUMN_C.gt(currentDate())), MY_TABLE.COLUMN_A ) .otherwise("NoChange"); // 可将表达式用于查询,比如SELECT语句 // dsl.select(caseExpr).from(MY_TABLE).fetch();
对应关系说明
DSL.when()对应SQL的when子句,多条件通过.and()串联,和SQL里的and逻辑一致le()方法等价于SQL的<=,gt()等价于>DSL.currentDate()直接对应SQL的current_date()函数.otherwise()对应SQL的else分支
内容的提问来源于stack exchange,提问作者Chedva
相关产品推荐
相关产品推荐

