Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/hibernate/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 如何获取行组的最大日期_Mysql_Hibernate - Fatal编程技术网

Mysql 如何获取行组的最大日期

Mysql 如何获取行组的最大日期,mysql,hibernate,Mysql,Hibernate,我希望在select语句中获取select语句的最新日期。我使用的是Hibernate,所以普通MySQL有一些限制,比如不能在from区域或MAX内部使用select语句 下面是一个测试结构: CREATE TABLE User ( username varchar(20) NOT NULL PRIMARY KEY, locationId int(10) NOT NULL ); CREATE TABLE UserRecords ( id int(10) NOT NULL AUTO

我希望在select语句中获取select语句的最新日期。我使用的是Hibernate,所以普通MySQL有一些限制,比如不能在from区域或MAX内部使用select语句

下面是一个测试结构:

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');
这就是我所追求的,并且经常工作,但在Hibernate中不工作:

SELECT 
   u.locationId, 
   MAX(
      SELECT 
         MAX(ur.recordDate) 
      FROM
         UserRecords
      WHERE 
         ur.username=u.username
   )
FROM 
   User u
GROUP BY
   u.locationId
我能得到的最接近的方法是列出每个用户的最大日期,然后在之后解析它们

SELECT 
    u.locationId, 
    GROUP_CONCAT(
       CONCAT('''',
          SELECT 
             MAX(ur.recordDate) 
          FROM
             UserRecords
          WHERE 
             ur.username=u.username
       , '''')
    )
 FROM 
    User u
 GROUP BY
    u.locationId

这真的很简单,但希望您能理解。

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

位置ID的最大记录日期 用户最大记录日期和位置ID 另一种方法:

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

请注意,如果一个组中的MAX(recordDate)值相同,则此方法可以为每个组返回多条记录。。因为它不处理关系。谢谢,很遗憾,在这种情况下我不能使用本机SQL查询。谢谢,很遗憾,我需要最大日期作为备用返回列,而不是主记录上的筛选器。您所说的“备用返回列”是什么意思?
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
select u.locationId, ur.recordDate
FROM User u
JOIN UserRecords ur on (ur.username = u.username)
ORDER BY ur.recordDate desc
LIMIT 1;