Thanks Lucas.
so I've narrowed this down.
My original CTE looks like this:
fun createTemporaryInnings(matchType: String, fieldingCteName: String): SelectHavingStep<Record2<Int, Int>> {
val selInningsNumber = select(
field("matchId"),
field("teamId"),
field("opponentsId"),
field("playerId"),
).from(fieldingCteName)
.where(field("inningsNumber", Int::class.java).eq(1))
.asTable("tid")
return select(
field("playerId", Int::class.java),
count().`as`("innings"),
).from(INNINGS)
.join(MATCHES).on(MATCHES.ID.eq(INNINGS.MATCHID))
.and(MATCHES.MATCHTYPE.eq(matchType))
.join(selInningsNumber)
.on(
field("innings.matchId").eq(field("tid.matchId"))
.and(field("innings.teamId").eq(field("tid.TeamId")))
)
.where(MATCHES.MATCHTYPE.eq(matchType))
.groupBy(field("tid.playerId"))
}
and the generated SQL looks like this (which is what I expect)
select playerId, count(*) as innings
from Innings
join Matches on (Matches.Id = Innings.MatchId and Matches.MatchType = 't')
join (select matchId, teamId, opponentsId, playerId
from tmp_fielding
where inningsNumber = 1) as tid
on (innings.matchId = tid.matchId and innings.teamId = tid.TeamId)
where Matches.MatchType = 't'
group by tid.playerId
So I have a nested select. Running this in the IDE takes about 1.5 seconds but from my code takes about 11 seconds.
If I replace the JOOQ nested query with SQL
fun createTemporaryInnings(matchType: String, fieldingCteName: String): SelectHavingStep<Record2<Int, Int>> {
val selInningsNumber = select(
field("matchId"),
field("teamId"),
field("opponentsId"),
field("playerId"),
).from(fieldingCteName)
.where(field("inningsNumber", Int::class.java).eq(1))
.asTable("tid")
return select(
field("playerId", Int::class.java),
count().`as`("innings"),
).from(INNINGS)
.join(MATCHES).on(MATCHES.ID.eq(INNINGS.MATCHID))
.join(
"(select matchId, teamId, opponentsId, playerId\n" +
" from tmp_fielding\n" +
" where inningsNumber = 1) as tid\n"
)
.on(
field("innings.matchId").eq(field("tid.matchId"))
.and(field("innings.teamId").eq(field("tid.TeamId")))
)
.where(MATCHES.MATCHTYPE.eq(matchType))
.groupBy(field("tid.playerId"))
}
Then the generated SQL is the same but the code now only takes 1.5 seconds to execute,
Kevin