简体   繁体   English

JOOQ / SQL如何基于外键选择最小日期

[英]JOOQ/SQL How to select min date based on foreign key

I have a table called Foo which contains 3 columns, (id, time, barId) and I would like to select all fields from Foo where the time (stored as a timestamp) is the lowest one in a group of barId. 我有一个名为Foo的表,其中包含3列(id,time,barId),我想从Foo中选择所有字段,其中,时间(存储为时间戳)是barId组中最低的字段。 For example if I had 例如,如果我有

Id, time, barId ID,时间,barId

1, 10am, 1 1、10am,1

2, 11am, 1 2,上午11点,1点

3, 10am, 2 3,10am,2

4, 9am, 2 4、9am,2

I would expect to receive back rows 1 and 4. 我希望收到第一行和第四行。

Currently I am using 目前我正在使用

.select(FOO.ID, FOO.TIME.min, FOO.BAR_ID)
   .from(FOO)
   .where()
   .groupBy(FOO.BAR_ID)
   .fetchInto(Foo.class);

And I am receiving an error stating column "foo.id" must appear in the GROUP BY clause or be used in an aggregate function 而且我收到一条错误消息,指出column "foo.id" must appear in the GROUP BY clause or be used in an aggregate function

The issue I had was that I was not grouping by the rows I was selecting. 我遇到的问题是我没有按选择的行进行分组。

The working code is 工作代码是

.select(FOO.ID, FOO.TIME.min, FOO.BAR_ID)
  .from(FOO)
  .where()
  .groupBy(FOO.ID, FOO.TIME, FOO.BAR_ID)
  .fetchInto(Foo.class);

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

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