How to re-use one CTE in another CTE in jOOQ

半城伤御伤魂 提交于 2020-01-05 04:09:13

问题


In jOOQ am re-using a CTE in a later CTE. I am trying to summarise student completion records by year and school. I am using jOOQ 3.11.2 and postgres 9.4.

I have working SQL code. However in jOOQ, I am getting null values returned.

This appears to be a problem with how I am re-using one CTE in a later CTE.

At first, I thought it might be a problem with the use of count(). From the manual, it looks like count() is being used correctly. As a test, I removed all reference to count() in the query and still get the same error.

I could not find examples of reusing or chaining CTEs in jOOQ. Easy enough in SQL, as shown here: SQL - Use a reference of a CTE to another CTE but I haven't got the hang of it in jOOQ.

When run in debug mode on Intellij, I see an error that the select() statement cannot be evaluated in the second CTE.

Cannot evaluate org.jooq.impl.SelectImpl.toString()

Here is a minimal example showing what I am doing.

 CommonTableExpression<Record4<String, String, String, Year>> cteOne = name("CteOne")
    .fields("SCHOOL","STUDENT_NAME", "COURSE_COMPLETED", "YEAR_COMPLETED")
    .as(
            select( a.NAME.as("SCHOOL")
                    , a.STUDENT_NAME
                    , a.COURSE_DESCRIPTION.as("courseCompleted"),
                    , a.YEAR_COMPLETED 
                    )
                    .from(a)
                    .orderBy(a.YEAR_COMPLETED)
    );

CommonTableExpression<Record3<String, Year, Integer >> cteCounts = name("cteCounts")

    .fields("SCHOOL", "YEAR_COMPLETED", "NUM_COMPLETED" )

    .as( with(cteOne)
                    .select(
                            , field(name("cteOne","SCHOOL"), String.class)
                            , field(name("cteOne","YEAR_COMPLETED"), Year.class)
                            , count().as("NUM_COMPS_LOGGED")
                    )
                    .from(cteOne)
                    .groupBy(
                            field(name("cteCompsList","YEAR_COMPLETED"), Year.class)
                          , field(name("cteOne","SCHOOL"), String.class)
                    )
                    .orderBy(
                            field(name("cteCompsList","YEAR_COMPLETED"), Year.class)
                          , field(name("cteOne","SCHOOL"), String.class)
                    )
    );

Can someone please point me in the right direction on this?


回答1:


Just like in your plain SQL version of your query, your cteCounts should not have a with(cteOne) clause:

WITH 
  cteOne (columns...) AS (select...),
  cteCounts (columns...) AS (select referencing cteOne, no "with cteOne" here...)
SELECT ...
FROM ...

Remove it and your query should be fine



来源:https://stackoverflow.com/questions/59232161/how-to-re-use-one-cte-in-another-cte-in-jooq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!