Mysql 选择具有不同值和最大日期的行
我有一个MySQL(5.1.49)表,有三列Mysql 选择具有不同值和最大日期的行,mysql,group-by,distinct,Mysql,Group By,Distinct,我有一个MySQL(5.1.49)表,有三列 mysql> create table testme(id int auto_increment, id2 int not null, somedate datetime, primary key(id)); 在我的例子中,id2不是唯一的,但我想返回具有不同id2值的行,其中maxsomedate mysql> select id, id2, max(somedate) from testme group by id2; +----+
mysql> create table testme(id int auto_increment, id2 int not null, somedate datetime, primary key(id));
在我的例子中,id2不是唯一的,但我想返回具有不同id2值的行,其中maxsomedate
mysql> select id, id2, max(somedate) from testme group by id2;
+----+-----+---------------------+
| id | id2 | max(somedate) |
+----+-----+---------------------+
| 1 | 5 | 2012-02-02 02:02:02 |
| 3 | 7 | 2010-01-10 11:01:33 |
+----+-----+---------------------+
下面是一些示例数据
mysql> insert into testme values (1, 5, '2012-01-02 01:01:01'),(2, 5, '2012-02-02 02:02:02'),(3, 7, '2010-01-10 11:01:33');
这几乎回答了我的问题,但是使用额外的id字段,返回的id和id2不匹配。对于id2=5,它将返回id=1,而不是id=2
mysql> select id, id2, max(somedate) from testme group by id2;
+----+-----+---------------------+
| id | id2 | max(somedate) |
+----+-----+---------------------+
| 1 | 5 | 2012-02-02 02:02:02 |
| 3 | 7 | 2010-01-10 11:01:33 |
+----+-----+---------------------+
我期待着
+----+-----+---------------------+
| id | id2 | max(somedate) |
+----+-----+---------------------+
| 2 | 5 | 2012-02-02 02:02:02 |
| 3 | 7 | 2010-01-10 11:01:33 |
+----+-----+---------------------+
需要与每个ID2的最长日期匹配的ID
有人有什么想法吗?谢谢不确定,但根据您的示例,尝试以下方法:
select max(id) as Id,id2,max(someDate) from testMe group by Id2
此查询肯定会起作用,尽管它可能不是最佳查询:
select t.id, s.id2, s.somedate
from testme t
join
( select id2, max(somedate) as somedate
from testme
group by id2
) s
on s.id2 = t.id2
and s.somedate = t.somedate;
您的问题的替代解决方案:
SELECT t0.id, t0.id2, t0.somedate
FROM testme AS t0
LEFT JOIN testme AS t1
ON t0.id2 = t1.id2
AND t1.somedate > t0.somedate
WHERE t1.id IS NULL;
与@itsmeee解决方案类似,如果id2,somedate
对不是唯一的,它将同时带来两行:
+----+-----+---------------------+
| id | id2 | somedate |
+----+-----+---------------------+
| 4 | 8 | 2012-02-02 02:02:02 |
| 6 | 8 | 2012-02-02 02:02:02 |
+----+-----+---------------------+
如果
id2,somedate
对不是唯一的,并且出于某种原因,每个id2
只需要一个结果,那么您可以让MySQL使用额外的GROUP BY t0.id2
子句为您选择一个。但请注意,这是非标准SQL行为 当要获取一组记录中的最大日期时,不建议将max(date)
与其他行组合。当然,您将始终获得max(date)
,但其他字段将是该集合中的第一个字段。以下是您的问题的答案,以您的表格为例:
+----+-----+---------------------+
| id | id2 | somedate |
+----+-----+---------------------+
| 1 | 5 | 2012-01-02 01:01:01 |
| 2 | 5 | 2012-02-02 02:02:02 |
| 3 | 7 | 2010-01-10 11:01:33 |
+----+-----+---------------------+
与@triclosan answer的评论相同。如果执行
插入testme(id,id2,somedate)值(4,8,'2012-02-02:02:02');在testme(id,id2,somedate)中插入值(5,8,'2010-01-02 01:01:01')
您的查询将返回52012-02-02 02:02:02
。正确,但我阅读了他的示例,并对他试图实现的目标进行了澄清。当我意识到我的答案不对时,我没有时间删除它。很抱歉