我在将以下语句转换为 jooq API
时遇到问题:
SELECT t1.col1, t1.col2, t1.col3, (SELECT count(*) FROM table2 where table2.col2 = t1.col1)
FROM table1 t1
我尝试使用 DSL.count()
和 DSL.selectCount()
但在寻找将 where 子句添加到 count 子查询的方法时失败了。
数据库是PostgreSQL 9.6。
最佳答案
卢卡斯建议使用 DSL.field
是更好的解决方案,因为它保留了 <T>
类型。
更多类型安全版本:
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();
我的第一个(类型安全性较低)解决方案:
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();
也许有一个更优雅的解决方案,但它确实有效。生成的查询看起来像我的原始查询。
关于java - JOOQ - 选择查询中的选择计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47870321/