简体   繁体   English

JOOQ如何从表中选择min'id'

[英]JOOQ How to select the min 'id' from a table

In mysql I want to execute a query like this 在mysql中我想执行这样的查询

SELECT MIN(id) FROM table;

The more I read about JOOQ syntax and the aggregate functions, the confused I get. 我读的关于JOOQ语法和聚合函数的内容越多,我就越感到困惑。

I thought something like this would work 我觉得这样的事情会起作用

select( EVENT.EVENTID , min() ).from( EVENT ).fetch();
or
Result<Integer> er = context.select( EVENT.EVENTID.min()).fetch();

I tried a work around by selecting the whole first record 我通过选择整个第一条记录尝试了一下

Result<EventRecord> er2 = context.selectFrom(EVENT).orderBy(EVENT.EVENTID.asc()).limit(1).fetch();

If the result has size 0, a record does not exist, but when it is not 0 I get the right record. 如果结果的大小为0,则记录不存在,但是当它不为0时,我得到正确的记录。 I would like to use the min() function but can't get the syntax right. 我想使用min()函数,但无法正确获取语法。

The query you want to write in SQL is this one: 您要在SQL中编写的查询是这样的:

SELECT MIN(event.eventid) FROM event

This is why your two attempts didn't work 这就是为什么你的两次尝试都无效

// 1. You cannot combine single columns with aggregate functions in SQL,
//    unless you're grouping by those columns
// 2. You didn't pass any cargument column to the MIN() function
context.select( EVENT.EVENTID , min() ).from( EVENT ).fetch();

// 3. This doesn't specify any FROM clause, so your database won't know what
//    table you want to select the MIN(eventid) from
context.select( EVENT.EVENTID.min()).fetch();

Note that these thoughts are not specific to jOOQ, they are related to SQL in general. 请注意,这些想法并非特定于jOOQ,它们通常与SQL有关。 When using jOOQ, always think of the SQL statement you want to express first (the one at the top of my answer). 使用jOOQ时,请始终考虑首先要表达的SQL语句(我的答案顶部的那个)。 So your jOOQ statement would look like any of these: 所以你的jOOQ语句看起来像这些:

// "Postfix notation" for MIN()
context.select(EVENT.EVENTID.min()).from(EVENT).fetch();

// "Prefix notation" for MIN(), where min() is static-imported from
// org.jooq.impl.DSL
context.select(min(EVENT.EVENTID)).from(EVENT).fetch();

It looks like the fetchAny() method will return the record with the first/lowest record id. 看起来fetchAny()方法将返回具有第一个/最低记录ID的记录。

EventRecord record = context.selectFrom(EVENT).fetchAny();

As @LukasEder mentioned there are many alternative methods, and he may be generous and follow up on some of those. 正如@LukasEder提到的那样,有许多替代方法,他可能会慷慨并跟进其中的一些方法。 Thanks Lucas 谢谢卢卡斯

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

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