如何获取行组的最大日期

46qrfjad  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(340)

我想在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');

这就是我所追求的,我经常工作,但在休眠状态下不工作:

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

这是真的精简,但希望你得到的想法。

yftpprvb

yftpprvb1#

看起来您正在尝试获取每个位置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

用户最大记录日期和位置ID

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

在hibernate中使用本机sql查询

pkmbmrz7

pkmbmrz72#

另一种方法:

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

相关问题