Kotlin Exposed框架编写含HAVING子句查询的实现问题咨询
正确实现代码
import org.jetbrains.exposed.sql.* import org.jetbrains.exposed.sql.transactions.transaction // 省略表定义部分,直接写查询逻辑 transaction { // 1. 定义表别名,和原生SQL的别名对齐 val pedidoContestacaoTable = PedidoContestacaoTable.alias("pc") val contestacaoEventTable = ContestacaoEventTable.alias("ce") // 2. 编写HAVING子句中的子查询 val latestStatusSubquery = contestacaoEventTable .slice(contestacaoEventTable[ContestacaoEventTable.status]) .select { // 关联条件和原生SQL对齐:事件表的纠纷ID = 外层纠纷表的ID contestacaoEventTable[ContestacaoEventTable.pedidoContestacaoId] eq pedidoContestacaoTable[PedidoContestacaoTable.id] } .orderBy(contestacaoEventTable[ContestacaoEventTable.createdAt] to SortOrder.DESC) .limit(1) // 3. 主查询实现 val result = PedidoTable .innerJoin(pedidoContestacaoTable, { PedidoTable.id }, { pedidoContestacaoTable[PedidoContestacaoTable.pedidoId] }) .slice(pedidoContestacaoTable.columns) .select { PedidoTable.number eq "1234" } .groupBy(pedidoContestacaoTable[PedidoContestacaoTable.id]) // 核心:用wrapAsExpression将单列子查询转为可比较的表达式 .having { wrapAsExpression(latestStatusSubquery) inList listOf("CAPTURED", "EXPIRED") } .map { it[pedidoContestacaoTable[PedidoContestacaoTable.id]] // 其他字段统一使用别名对象取值即可 } result.forEach { println(it) } }
关键修正点说明
- 原代码子查询关联条件错误:原生SQL是
ce.pedido_contestacao_id = pc.id,你之前写的是事件表ID关联纠纷表ID,逻辑完全不匹配,是主要报错原因之一 - 单列limit 1的子查询不需要额外加alias,直接用
wrapAsExpression()包裹整个子查询对象,就可以当成普通字段调用inList方法 - 主查询用了别名后的
pedidoContestacaoTable,所有取值、关联条件都要统一用别名,不能混合原表和别名表的字段,否则会生成错误的SQL - Kotlin中字符串常量要用双引号,你原代码里
eq '1234'的单引号是字符类型写法,会报类型不匹配错误
内容的提问来源于stack exchange,提问作者Claudivan Moreira
相关产品推荐
相关产品推荐

