Mysql - 如何使用GROUP BY获取最后一条记录

时间:2014-02-25 09:13:16

标签: mysql

我有一张如下表:

id   |   deptid   |   last_activities
1    |     1      |   MMD PURCASHING
2    |     1      |   JKO / REPORTING
3    |     2      |   STAND BY CC
4    |     3      |   JKO / REPORTING

我的查询:

SELECT id, deptid, last_activities FROM dept_activities GROUP BY deptid ORDER BY id DESC

结果如下:

id   |   deptid   |   last_activities
4    |     3      |   JKO / REPORTING
3    |     2      |   STAND BY CC
1    |     1      |   MMD PURCASHING

我想要这样的结果:

id   |   deptid   |   last_activities
4    |     3      |   JKO / REPORTING
3    |     2      |   STAND BY CC
2    |     1      |   JKO / REPORTING

怎么可能?如何正确查询?

2 个答案:

答案 0 :(得分:3)

请试试这个:

SELECT * FROM dept_activities AS da1
JOIN
(SELECT MAX(id) as max_id FROM dept_activities GROUP BY deptid DESC) AS da2
ON (da1.id = da2.max_id);

答案 1 :(得分:1)

使用子查询获取每个deptid的最大ID,然后将其连接到表格,可以得到如下内容: -

SELECT a.id, a.deptid, a.last_activities
FROM dept_activities a
INNER JOIN
(
    SELECT MAX(id) AS MaxId, deptid
    FROM dept_activities 
    GROUP BY deptid 
) Sub1
ON a.deptid = Sub1.deptid
AND a.id = Sub1.MaxId
ORDER BY a.id DESC

使用GROUP_CONCAT的另一种可能的解决方案,虽然不热衷于此(如果last_activity包含您用于GROUP_CONCAT的分隔符,则会失败)。

SELECT MAX(id), deptid, SUBSTRING_INDEX(GROUP_CONCAT(last_activities ORDER BY id DESC), ',', 1)
FROM dept_activities 
GROUP BY a.deptid