首页 > 解决方案 > 如何使用 jooq 访问子查询列?

问题描述

我无法理解如何从子查询(MySQL)访问列。这是我的代码:

Personne personne = Personne.PERSONNE.as("personne");
Evenement evenement = Evenement.EVENEMENT.as("evenement");
Genealogie genealogie = Genealogie.GENEALOGIE.as("genealogie");
Lieu lieu = Lieu.LIEU.as("lieu");

SelectField<?>[] select = { DSL.countDistinct(personne.ID).as("countRs"), lieu.LIBELLE.as("libelleRs"),
lieu.ID.as("idVille") };

Table<?> fromPersonne = evenement.innerJoin(personne).on(personne.ID.eq(evenement.IDPERS))
.innerJoin(genealogie).on(genealogie.ID.eq(personne.IDGEN)).innerJoin(lieu)
.on(lieu.ID.eq(evenement.IDLIEU));

Table<?> fromFamille = evenement.innerJoin(personne).on(personne.IDFAM.eq(evenement.IDFAM))
.innerJoin(genealogie).on(genealogie.ID.eq(personne.IDGEN)).innerJoin(lieu)
.on(lieu.ID.eq(evenement.IDLIEU));

GroupField[] groupBy = { lieu.ID };

Condition condition = //conditionally build, not relevant i think

result = create.select(DSL.asterisk())
                    .from(create.select(select).from(fromPersonne).where(condition).groupBy(groupBy)
                            .union(create.select(select).from(fromFamille).where(condition).groupBy(groupBy)))
                    
// i would like something like this but i don't know how:  .groupBy(groupBy).fetch();

基本上我所拥有的是:

SELECT
*
FROM(

(SELECT
countRs, libelleRs, idVille
FROM
fromPersonne
WHERE
-- conditions
GROUP BY lieu.ID)

UNION 

(SELECT
countRs, libelleRs, idVille
FROM
fromFamille
WHERE
-- conditions
GROUP BY lieu.ID)

)GROUP BY lieu.ID -- this is where i need help

在一个普通的 MySQL 查询中,我只需给联合一个别名,然后引用我想group by使用别名的列,但它似乎不适用于 JOOQ。我只需要将子查询的结果组合在一起,但我不知道如何引用子查询列...我确信我必须在“主选择”之外的对象中引用我的子查询能够访问这些行中的列或其他内容,但我迷失在所有对象类型中。

标签: mysqljooq

解决方案


您必须将派生表分配给局部变量并从中取消引用列,例如

Table<?> t = table(
  select(...).from(...).groupBy(...).unionAll(select(...).from(...).groupBy(...))
).as("t");

Field<Integer> tId = t.field(lieu.ID);

推荐阅读