如何在 jOOQ 中编写计数查询

2022-09-01 10:11:40

我正在将纯SQL转换为jOOQ,现在我有这个

("SELECT Count(*) Count From Table "); 

我必须用jOOQ写这个,我们怎么能写它?

selectQueryRecord.addSelect(Here Count Function );
selectQueryRecord.addFrom(Table);

答案 1

实现你所请求的最直接的方法是,通过使用 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()selectfetchOne()

int count =
DSL.using(configuration)
   .fetchCount(DSL.selectFrom(Table));

但请注意,这会像这样呈现嵌套选择:

SELECT COUNT(*) FROM (SELECT a, b, ... FROM Table)

答案 2

我使用以下语法:

import org.jooq.impl.DSL.count

... 

int count = 
DSL.using(configuration)
   .selectCount()
   .from(Table)
   .fetchOne(count());

这不那么冗长,更简单。

卢卡斯的答案可以追溯到2013年,也许这个解决方案在当时并不存在。


推荐