JOOQ如何选择min' id'从一张桌子

时间:2014-06-23 03:43:24

标签: java sql jooq

在mysql中我想执行像这样的查询

SELECT MIN(id) FROM table;

我读的关于JOOQ语法和聚合函数的内容越多,我就越感到困惑。

我认为这样的事情会起作用

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

我通过选择整个第一条记录来尝试解决方法

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

如果结果的大小为0,则记录不存在,但是当记录不为0时,我会得到正确的记录。我想使用min()函数,但无法正确使用语法。

2 个答案:

答案 0 :(得分:5)

您要在SQL中编写的查询是这样的:

SELECT MIN(event.eventid) FROM event

这就是为什么你的两次尝试都没有效果

// 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();

请注意,这些想法并非特定于jOOQ,它们通常与SQL有关。使用jOOQ时,请始终考虑首先要表达的SQL语句(我的答案顶部的那个)。所以你的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();

答案 1 :(得分:0)

看起来fetchAny()方法将返回具有第一个/最低记录ID的记录。

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

正如@LukasEder所提到的,有许多替代方法,他可能会慷慨并跟进其中的一些方法。谢谢卢卡斯