I have a problem while converting the following statement into jooq API
:
SELECT t1.col1, t1.col2, t1.col3, (SELECT count(*) FROM table2 where table2.col2 = t1.col1)
FROM table1 t1
I tried it with DSL.count()
and DSL.selectCount()
but I failed while searching a way to add the where clause to the count subquery.
The database is PostgreSQL 9.6.
Lukas suggestion to use DSL.field
is the better solution because it preserves the <T>
type.
More typesafe version:
TableField<Table1Record, Long> col1 = TABLE1.COL1;
Field<Integer> count = DSL.field(DSL.selectCount().from(TABLE2).where(TABLE2.COL2.eq(col1)));
using(configuration).select(col1, count).from(TABLE1).fetch();
My first (less typesafe) solution:
TableField<Table1Record, Long> col1 = TABLE1.COL1;
Field count = DSL.selectCount().from(TABLE2).where(TABLE2.COL2.eq(col1)).asField("count");
using(configuration).select(col1, count).from(TABLE1).fetch();
Maybe there is a more elegant solution, but it works. The generated query looks like my original query.
Here is another example using DSL.field(...)
:
Field<Integer> COUNT = DSL.field("COUNT(*) OVER ()", Integer.class);
List<Map<String, Object>> records = DSL.select(ACCESSORY.ID,
ACCESSORY.NAME,
ACCESSORY.TYPE,
ACCESSORY.PRICE,
BRAND.NAME,
COUNT.as("total"))
.from(ACCESSORY)
.innerJoin(BRAND).onKey()
.fetchMaps();
The ResultSet will contain a column called total
which will be treated as a type java.lang.Integer
. This works with PostgreSQL 9.6.
A detailed description of COUNT(*) OVER ()
can be found here: here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.