【问题标题】:How to access columns of subqueries with jooq?如何使用 jooq 访问子查询列?
【发布时间】:2020-11-20 07:56:34
【问题描述】:

我无法理解如何从子查询 (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。 我只需要将子查询的结果组合在一起,但我不知道如何引用子查询列...我确信我必须在“主选择”之外的对象中引用我的子查询能够访问这些行中的列或其他内容,但我迷失在所有对象类型中。

【问题讨论】:

    标签: mysql jooq


    【解决方案1】:

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

    Table<?> t = table(
      select(...).from(...).groupBy(...).unionAll(select(...).from(...).groupBy(...))
    ).as("t");
    
    Field<Integer> tId = t.field(lieu.ID);
    

    【讨论】:

    • 非常感谢,你肯定无处不在!
    猜你喜欢
    • 1970-01-01
    • 2019-05-09
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 2022-01-19
    • 2020-08-14
    • 1970-01-01
    • 2017-09-27
    相关资源
    最近更新 更多