MySQL MAX Date - 单个连接表 - 仅选择第一个fkUserId匹配

时间:2015-02-04 18:03:59

标签: mysql

简单连接表 -

CREATE TABLE tbluserstomaintasks  (
fkUserId INT(6),
fkMainTaskId INT(6),
UpdateTimestamp TIMESTAMP
);

INSERT INTO tbluserstomaintasks (fkUserId, fkMainTaskId, UpdateTimestamp) VALUES (1, 1, '2015-02-03 16:40:00');
INSERT INTO tbluserstomaintasks (fkUserId, fkMainTaskId,  UpdateTimestamp) VALUES (1, 2, '2015-02-03 16:47:00');
INSERT INTO tbluserstomaintasks (fkUserId, fkMainTaskId, UpdateTimestamp) VALUES (1, 2, '2015-02-03 16:53:00');
INSERT INTO tbluserstomaintasks (fkUserId, fkMainTaskId, UpdateTimestamp) VALUES (2, 1, '2015-02-03 17:01:00');

SQL SELECT查询一个特定fkUserId的最新UpdateTimestamp

SELECT  p2.fkUserId, p2.fkMainTaskId, p2.UpdateTimestamp
FROM tbluserstomaintasks AS p2
  INNER JOIN
  (SELECT fkUserId, fkMainTaskId, MAX(UpdateTimestamp) AS Value
  FROM tbluserstomaintasks
  GROUP BY fkUserId)
 AS p1
 ON p1.fkUserId = p2.fkUserId AND p1.Value = p2.UpdateTimestamp
 WHERE p2.fkUserId = 1

结果

fkUserID fkMainTaskId UpdateTimestamp 1 2 2015-02-03 16:53:00

我正在寻找一个包含两条记录的结果集,一条是fkMainTaskId = 1(UpdateTimestamp = 2015-02-03 16:40:00),另一条是fkMainTaskId = 2(UpdateTimestamp = 2015-02- 03 16:53:00)。

尝试#2: 已移动' WHERE fkUserId = 1'到内部SELECT,结果与尝试#1相同。

尝试#3: 从外部SELECT(p1.fkUserId = p2.fkUserId)中删除了第一个ON子句,其结果与尝试#1相同。

1 个答案:

答案 0 :(得分:0)

此查询应该适合您。您希望每个用户和任务ID都有一行,每个用户都有最大时间戳。

SELECT  p2.fkUserId, p2.fkMainTaskId, MAX(p2.UpdateTimestamp)
FROM tbluserstomaintasks AS p2
WHERE p2.fkUserId = 1
GROUP BY p2.fkUserId, p2.fkMainTaskId