I'm (very!) new to jOOQ and I want to write a statement that gets me the number off all references of a certain id in different tables.
So for example I have a dataset from the table book of the schema book (-> book.book) with the PK 45. This books PK is referred in different tables in different schemas:
- table author in schema author (-> author.author)
- table publisher in schema publisher (-> publisher.publisher)
- table series in schema series (-> series.series)
I tried to use UNION ALL to combine the different results but after hours trying around I still just cant get the hang of it. Especially with the via the "as()" function created field "cnt". This is what I have so far:
final Result<T> record = context
.select(DSL.sum())
.from(
context
.select(DSL.count(AUTHOR_TABLE.BOOK_REF).as("cnt"))
.from(AUTHOR_TABLE)
.where(AUTHOR_TABLE.BOOK_REF.eq(bookRef))
.unionAll(
context
.select(DSL.count(PUBLISHER_TABLE.BOOK_REF))
.from(PUBLISHER_TABLE)
.where(PUBLISHER_TABLE.BOOK_REF.eq(bookRef))
)
.unionAll(
context
.select(DSL.count(SERIES_TABLE.BOOK_REF))
.from(SERIES_TABLE)
.where(SERIES_TABLE.BOOK_REF.eq(bookRef))
)
)
.fetchOne();
My SQL statement that I used as a reference is working just fine and looks like that:
SELECT SUM(cnt) FROM (
SELECT COUNT(*) as cnt FROM author.author WHERE book_ref = 45
UNION ALL
SELECT COUNT(*) FROM publisher.publisher WHERE book_ref = 45
UNION ALL
SELECT COUNT(*) FROM series.series WHERE book_ref = 45
) a
Can anyone help me to complete this statement? Thanks in advance :)