简体   繁体   English

如何在 jOOQ 中编写计数查询

[英]How to write Count Query In jOOQ

I am converting Pure SQL to jOOQ now I have this我正在将 Pure SQL 转换为 jOOQ 现在我有了这个

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

I have to write this in jOOQ how can we write it?我必须在jOOQ中写这个我们怎么写?

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

The most straight-forward way to implement what you're requesting is this, by using selectCount() :通过使用selectCount()来实现您所请求的最直接的方法是:

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

Alternatively, you can explicitly express the count() function:或者,您可以显式表达count()函数:

int count = 
DSL.using(configuration)
   .select(DSL.count())
   .from(Table)
   .fetchOne(0, int.class);

There's another alternative for fetching a count(*) of any arbitrary select expression, which helps you avoid specifying the result column index and type in the above fetchOne() method.还有另一种方法可以获取任意select表达式的count(*) ,它可以帮助您避免在上述fetchOne()方法中指定结果列索引和类型。 This uses fetchCount() :这使用fetchCount()

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

Beware, though, that this renders a nested select like this:但是请注意,这会呈现这样的嵌套选择:

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

I use the following syntax for this:我为此使用以下语法:

import org.jooq.impl.DSL.count

... 

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

This is less verbose and simpler.这不那么冗长和简单。

Lukas's answer dates from 2013, maybe this solution did not exist at the time. Lukas 的回答可以追溯到 2013 年,也许当时这个解决方案并不存在。

这是我们必须像这样使用的解决方案

  selectQueryRecord.fetchCount();

我用过这个:

Integer count = DSL.selectCount().from(Table).where(Table.FIELD.eq(value)).fetchOneInto(Integer.class);

NOTE:笔记:

Deprecated.已弃用。 - 3.5.0 - [#3356] - This method is being removed as it is confusingly different from all the other types of ResultQuery.fetch() methods, in that it modifies the original Select statement by wrapping it. - 3.5.0 - [#3356] - 此方法被删除,因为它与所有其他类型的 ResultQuery.fetch() 方法不同,因为它通过包装它来修改原始 Select 语句。 In particular, this method can be easily confused with ResultQuery.fetch(Field), or more concretely fetch(count()), which has an entirely different semantics.特别是,这个方法很容易与 ResultQuery.fetch(Field) 混淆,或者更具体地说 fetch(count()) ,它们具有完全不同的语义。 Use DSLContext.fetchCount(Select) instead.使用 DSLContext.fetchCount(Select) 代替。 Execute this query in the context of its attached executor and return a COUNT(*) value.在其附加执行程序的上下文中执行此查询并返回 COUNT(*) 值。

I think the proper way to write get the count would be like this:我认为写 get 计数的正确方法是这样的:

 SelectQuery<Record> selectQueryCount = transaction.selectQuery();
 selectQueryCount.addFrom(Table);
 
 Result<Record> resultObject = selectQueryRecord.fetchCount();

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

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