简体   繁体   English

JOOQ-选择查询中的选择计数

[英]JOOQ - Select count inside select query

I have a problem while converting the following statement into jooq API : 将以下语句转换为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. 我用DSL.count()DSL.selectCount()尝试,但是在搜索将where子句添加到count子查询的方法时失败了。

The database is PostgreSQL 9.6. 该数据库是PostgreSQL 9.6。

Lukas suggestion to use DSL.field is the better solution because it preserves the <T> type. Lukas建议使用DSL.field是更好的解决方案,因为它保留了<T>类型。

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(...) : 这是使用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 . ResultSet将包含名为total的列,该列将被视为类型java.lang.Integer This works with PostgreSQL 9.6. 这适用于PostgreSQL 9.6。

A detailed description of COUNT(*) OVER () can be found here: here . COUNT(*) OVER ()的详细描述可以在这里找到: 这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM