当使用group by时,mysql选择一个字段最大行

时间:2018-09-07 02:14:36

标签: mysql

mysql> select * from test;
+----+--------+------+------------+---------+
| id | title  | tag  | date       | content |
+----+--------+------+------------+---------+
| 38 | title1 | xx   | 1514521364 | 1       |
| 39 | title2 | xx   | 1514521365 | 1       |
| 40 | title3 | xx   | 1514521366 | 1       |
| 41 | title4 | xx   | 1514521367 | 2       |
| 42 | title5 | xx   | 1514521368 | 2       |
+----+--------+------+------------+---------+
5 rows in set (0.01 sec)

这是我的测试表。我需要得到如下结果:

+----+--------+------+------------+---------+
| id | title  | tag  | date       | content |
+----+--------+------+------------+---------+
| 40 | title3 | xx   | 1514521366 | 1       |
| 42 | title5 | xx   | 1514521368 | 2       |
+----+--------+------+------------+---------+

我按content字段分组,并且需要按max(date)选择行,因为我需要正确的id字段。

sql可能喜欢select id, max(date), content from test group by content;

我尝试了一些方法,但是失败了。我真的是mysql的新秀。

2 个答案:

答案 0 :(得分:0)

尝试一下:-

SELECT *
FROM test
WHERE date IN (SELECT MAX(date)
               FROM test GROUP BY content);

答案 1 :(得分:0)

此查询将执行您想要的操作。根据内容和日期匹配,JOIN将表格归为每个内容的最大日期列表,从而为您提供idtitle和{{1}的正确值}:

tag

输出:

SELECT t.*
FROM test t
JOIN (SELECT content, MAX(date) AS maxdate
      FROM test
      GROUP BY content) t1
ON t1.content = t.content AND t1.maxdate = t.date

SQLFiddle Demo