如何获取行组的最大日期

时间:2018-08-23 17:30:02

标签: mysql hibernate

我希望在select语句中获取select语句的最新日期。我正在使用Hibernate,因此对于普通的MySQL有局限性,例如不能在from区域或MAX内部具有select语句。

这是一个测试结构:

if (count>1)

这是我所追求的并且可以正常工作,但是在Hibernate中不起作用:

if(count>1)
{
    t = head; // <------- new line
    while(t->link!=NULL)
    {
        t=t->link;
    }
    temp->link=t->link;
    t->link=temp;
} 

我能得到的最接近的方法是只列出每个用户的最大日期,然后在之后解析它们。

CREATE TABLE User (
  username varchar(20) NOT NULL PRIMARY KEY,
  locationId int(10) NOT NULL
);

CREATE TABLE UserRecords (
  id int(10) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  username varchar(20) NOT NULL,
  recordDate datetime NOT NULL
);

INSERT INTO User VALUES ('test',1);
INSERT INTO User VALUES ('test2',2);
INSERT INTO User VALUES ('test3',1);

INSERT INTO UserRecords VALUES (null,'test','2018-02-10 14:29:40');
INSERT INTO UserRecords VALUES (null,'test2','2018-03-11 12:21:10');
INSERT INTO UserRecords VALUES (null,'test3','2018-05-18 11:11:15');
INSERT INTO UserRecords VALUES (null,'test','2018-06-20 16:58:50');

这确实很简单,但希望您能明白。

2 个答案:

答案 0 :(得分:1)

看起来您正在尝试获取每个位置ID的最长记录日期,这可以通过加入巢状子查询来实现

位置ID的最长记录日期

SELECT
  u.locationId,
  Max(urRecordDate.maxRecordDate)
FROM User u
  INNER JOIN
  (SELECT
     ur.username,
     MAX(ur.recordDate) AS maxRecordDate
   FROM UserRecords ur
   GROUP BY ur.username) AS urRecordDate
    ON u.username = urRecordDate.username
GROUP BY u.locationId

用户的最大记录日期和locationId

SELECT
  u.locationId,
  urRecordDate.maxRecordDate
FROM User u
  INNER JOIN
  (SELECT
     ur.username,
     MAX(ur.recordDate) AS maxRecordDate
   FROM UserRecords ur
   GROUP BY ur.username) AS urRecordDate
    ON u.username = urRecordDate.username

using native SQL queries in hibernate

答案 1 :(得分:0)

另一种方法:

select u.locationId, ur.recordDate
FROM User u
JOIN UserRecords ur on (ur.username = u.username)
ORDER BY ur.recordDate desc
LIMIT 1;