You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JOOQ中实现MySQL的SUM嵌套IF条件查询?

Translating Your MySQL Query to jOOQ

Got it, let's break down how to replicate your MySQL query logic in jOOQ. I'll show you a couple of approaches that match your original SQL perfectly, depending on whether you prefer jOOQ's native condition API or a direct 1:1 mapping of MySQL's IF function.

First, assuming you've already set up your jOOQ code generation (so you have generated table/field references like TABLE.COLUMN1, etc.), here's the implementation:

This is jOOQ's idiomatic way to handle conditional logic, and it's more readable in Java code:

import org.jooq.DSLContext;
import static org.jooq.impl.DSL.*;

// Your configured DSLContext instance
DSLContext dsl = ...;

var result = dsl.select(
        // Equivalent to SUM(IF(COLUMN1 > COLUMN2, COLUMN2, COLUMN1))
        sum(when(TABLE.COLUMN1.greaterThan(TABLE.COLUMN2), TABLE.COLUMN2)
                .otherwise(TABLE.COLUMN1))
                .as("sum_min_col1_col2"),
        
        // Equivalent to SUM(IF(COLUMN3 = 0, 4, 10))
        sum(when(TABLE.COLUMN3.eq(0), inline(4))
                .otherwise(inline(10)))
                .as("sum_conditional_col3")
)
.from(TABLE)
.fetchOne();

Direct Mapping to MySQL's IF Function

If you want the generated SQL to mirror your original query exactly, you can use jOOQ's if_ function (the underscore avoids conflict with Java's if keyword):

import org.jooq.DSLContext;
import static org.jooq.impl.DSL.*;

DSLContext dsl = ...;

var result = dsl.select(
        // Exact match for SUM(IF(COLUMN1 > COLUMN2, COLUMN2, COLUMN1))
        sum(if_(TABLE.COLUMN1.greaterThan(TABLE.COLUMN2), TABLE.COLUMN2, TABLE.COLUMN1))
                .as("sum_min_col1_col2"),
        
        // Exact match for SUM(IF(COLUMN3 = 0, 4, 10))
        sum(if_(TABLE.COLUMN3.eq(0), inline(4), inline(10)))
                .as("sum_conditional_col3")
)
.from(TABLE)
.fetchOne();

Key Notes:

  • inline(4) and inline(10) tell jOOQ to treat these as literal values in the generated SQL, ensuring correct type handling.
  • Both approaches will generate SQL that behaves exactly like your original query. The when/otherwise API is more portable across databases if you ever need to switch away from MySQL, while if_ is MySQL-specific but matches your original code structure.

Once you run this, you can extract the results using result.get("sum_min_col1_col2", Long.class) (or whatever numeric type matches your columns) and result.get("sum_conditional_col3", Long.class).

内容的提问来源于stack exchange,提问作者Anurag Sahu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:51:17