在没有主键的情况下检索每个组中的最后一条记录

时间:2016-06-08 09:42:03

标签: mysql sql group-by sql-order-by greatest-n-per-group

我有一张表来记录用户上次登录的详细信息

event_name userID value                  created_at
-------------------------------------------------------------
last_login 12    2016-06-02 11:06:29    2016-06-02 11:06:29 
last_login 12    2016-06-02 10:16:11    2016-06-02 10:16:11     
last_login 14    2016-06-02 10:11:13    2016-06-02 10:11:13     
last_login 17    2016-05-02 10:16:29    2016-05-02 10:16:29     
last_login 14    2016-05-02 10:15:11    2016-06-02 10:15:11     

预期结果:

event_name userID value                  created_at
-------------------------------------------------------------
last_login 12    2016-06-02 11:06:29    2016-06-02 11:06:29 
last_login 14    2016-06-02 10:11:13    2016-06-02 10:11:13     
last_login 17    2016-05-02 10:16:29    2016-05-02 10:16:29     

我想通过UserId获取此表信息组,我通过created_at命令并在timesAgo fromat中显示值(例如1小时前),但我没有获得使用group by的最新记录,例如,userID = 12 I我的价值= 2016-06-02 10:16:11而不是价值= 2016-06-02 11:06:29

2 个答案:

答案 0 :(得分:1)

如果我理解正确,您可以使用NOT EXISTS()

来实现这一目标
SELECT * FROM YourTable t
WHERE NOT EXISTS(SELECT 1 FROM YourTable s
                 WHERE s.created_at > t.created_at
                    AND s.userID = t.userID)

答案 1 :(得分:1)

试试这个。

首先,我从created_at和userID获得最大值,然后我加入以获得孔行

SELECT d.* FROM (
  SELECT 
      userID, MAX(created_at)  AS created_at
  FROM
      tablename 
  GROUP BY userID ) AS `keys`
LEFT JOIN tablename d ON 
  d.userID = `keys`.userID
  AND 
 d.created_at = `keys`.created_at;

<强>示例

MariaDB []> SELECT d.* FROM (
    ->   SELECT
    ->       userID, MAX(created_at)  AS created_at
    ->   FROM
    ->       tablename
    ->   GROUP BY userID ) AS `keys`
    -> LEFT JOIN tablename d ON
    ->   d.userID = `keys`.userID
    ->   AND
    ->  d.created_at = `keys`.created_at;
+--------+----------------------------+
| userID | created_at                 |
+--------+----------------------------+
|      1 | 0000-00-00 00:00:00.000000 |
|      2 | 2016-06-03 13:16:07.000000 |
+--------+----------------------------+
2 rows in set (0.00 sec)

MariaDB []>