对多个计数字段求和

Sum over multiple count field

我尝试使用 JOOQ 和 MySQL 数据库对多个计数字段求和。

目前我的代码如下所示:

int userId = 1;
Field<Object> newField = DSL.select(DSL.count()).from(
                DSL.select(DSL.count())
                        .from(REQUIREMENT)
                        .where(REQUIREMENT.CREATOR_ID.equal(userId))
                        .unionAll(DSL.select(DSL.count())
                                .from(REQUIREMENT) 
                                .where(REQUIREMENT.LEAD_DEVELOPER_ID.equal(userId)))

始终 returns 2 作为新字段。但我想知道有多少次用户是需求的创建者加上需求的主要开发人员。

你说“sum over multiple count”,但这不是你在做什么。您执行“计数 计数”。解决方案当然是这样的:

// Assuming this to avoid referencing DSL all the time:
import static org.jooq.impl.DSL.*;

 select(sum(field(name("c"), Integer.class)))
.from(
     select(count().as("c"))
    .from(REQUIREMENT)
    .where(REQUIREMENT.CREATOR_ID.equal(userId))
    .unionAll(
     select(count().as("c"))
    .from(REQUIREMENT) 
    .where(REQUIREMENT.LEAD_DEVELOPER_ID.equal(userId)))
);

或者,如果您打算将更多这些计数添加到总和中,这可能是一个更快的选择:

 select(sum(choose()
    .when(REQUIREMENT.CREATOR_ID.eq(userId)
        .and(REQUIREMENT.LEAD_DEVELOPER_ID.eq(userId)), inline(2))
    .when(REQUIREMENT.CREATOR_ID.eq(userId), inline(1))
    .when(REQUIREMENT.LEAD_DEVELOPER_ID.eq(userId), inline(1))
    .otherwise(inline(0))
 ))
.from(REQUIREMENT);

More details about the second technique in this blog post