如何在 JooQ 中正确表达这个 SQL 查询?我确实知道 arrayAggDistinct() DSL 方法,但我很难表达行类型。
SELECT
u.user_id,
ARRAY_AGG(DISTINCT (g.group_id, g.group_name)) AS grouped_groups,
ARRAY_AGG(DISTINCT (a.authority_id, a.authority)) AS grouped_authorities
FROM users u
LEFT JOIN group_members gm ON u.user_id = gm.user_id
LEFT JOIN groups g ON gm.group_id = g.group_id
LEFT JOIN group_authorities ga ON g.group_id = ga.group_id
LEFT JOIN authorities a ON ga.authority_id = a.authority_id
GROUP BY u.user_id;
编辑我发现,这创建了正确的查询
val groupRow: Row2<Long?, String?> = row(GROUPS.GROUP_ID, GROUPS.GROUP_NAME)
val groupsField: Field<Record2<Long?, String?>> = PostgresDSL.rowField(groupRow)
val authorityRow: Row2<Long?, String?> = row(AUTHORITIES.AUTHORITY_ID, AUTHORITIES.AUTHORITY)
val authoritiesField: Field<Record2<Long?, String?>> = PostgresDSL.rowField(authorityRow)
val jooqQuery = PostgresDSL.select(
*USERS.fields(),
arrayAggDistinct(groupsField).`as`("groups"),
arrayAggDistinct(authoritiesField).`as`("authorities"),
).from(USERS)
.leftJoin(GROUP_MEMBERS).on(USERS.USER_ID.eq(GROUP_MEMBERS.USER_ID))
.leftJoin(GROUPS).on(GROUP_MEMBERS.GROUP_ID.eq(GROUPS.GROUP_ID))
.leftJoin(GROUP_AUTHORITIES).on(GROUPS.GROUP_ID.eq(GROUP_AUTHORITIES.GROUP_ID))
.leftJoin(AUTHORITIES).on(GROUP_AUTHORITIES.AUTHORITY_ID.eq(AUTHORITIES.AUTHORITY_ID))
.where(USERS.MAIL.eq(mail))
.groupBy(*USERS.fields())
但是 rowField 方法已被标记为已弃用,并且建议的 rowN 替代方法不是在 arrayAggDistinct 中使用的正确类型。
有许多问题要求
Row[N]
类型扩展 SelectField
,但不扩展 Field
,在整个 API 中得到更普遍的接受,请参见例如:
jOOQ 没有广泛支持这些的主要原因是,很难向用户传达这些东西往往在 PostgreSQL 中工作但在其他地方几乎不起作用,所以例如Oracle、MySQL、SQL Server 用户会不断对 jOOQ API 看似承诺但未兑现的问题感到失望。
在有办法彻底模拟这些事情之前,您必须使用
PostgresDSL
(或您自己的纯 SQL 模板)来解决问题。