如何在 jOOQ 中编写计数查询
我正在将纯SQL转换为jOOQ,现在我有这个
("SELECT Count(*) Count From Table ");
我必须用jOOQ写这个,我们怎么能写它?
selectQueryRecord.addSelect(Here Count Function );
selectQueryRecord.addFrom(Table);
我正在将纯SQL转换为jOOQ,现在我有这个
("SELECT Count(*) Count From Table ");
我必须用jOOQ写这个,我们怎么能写它?
selectQueryRecord.addSelect(Here Count Function );
selectQueryRecord.addFrom(Table);
实现你所请求的最直接的方法是,通过使用 selectCount()
:
int count =
DSL.using(configuration)
.selectCount()
.from(Table)
.fetchOne(0, int.class);
或者,您可以显式表示 count()
函数:
int count =
DSL.using(configuration)
.select(DSL.count())
.from(Table)
.fetchOne(0, int.class);
获取任意表达式的 count(*)
还有另一种方法,可帮助您避免在上述方法中指定结果列索引和类型。这使用 fetchCount()
:select
fetchOne()
int count =
DSL.using(configuration)
.fetchCount(DSL.selectFrom(Table));
但请注意,这会像这样呈现嵌套选择:
SELECT COUNT(*) FROM (SELECT a, b, ... FROM Table)
我使用以下语法:
import org.jooq.impl.DSL.count
...
int count =
DSL.using(configuration)
.selectCount()
.from(Table)
.fetchOne(count());
这不那么冗长,更简单。
卢卡斯的答案可以追溯到2013年,也许这个解决方案在当时并不存在。