mysql查询出最后日期的记录,MySQL从多个获取最后日期记录

I have the following in my db:

ID datetime type value

1094 2013-09-25 09:11:18 HDD 89%

1094 2013-09-25 09:11:18 CPU 55%

1093 2013-09-25 09:11:18 HDD 77%

1093 2013-09-25 09:11:18 CPU 55%

1094 2013-09-25 08:21:28 HDD 85%

1094 2013-09-25 08:21:28 CPU 11%

1093 2013-09-25 07:04:00 HDD 76%

I want to get the last date for every ID and type record:

1094 2013-09-25 09:11:18 HDD 89%

1094 2013-09-25 09:11:18 CPU 55%

1093 2013-09-25 09:11:18 HDD 77%

1093 2013-09-25 09:11:18 CPU 55%

解决方案

You can use GROUP BY, but it's important to understand how it works.

When you use GROUP BY a group of rows is collapsed into one and what is displayed in the other columns that are not used in your GROUP BY clause, is determined either by using aggregate functions or it is a random row out of that group. You can't be sure to get the row corresponding to the row displayed holding the MAX() value or whatever aggregate function you used. This becomes especially obvious, when you do a query like:

SELECT id, MIN(whatever), MAX(whatever), another_column

FROM your_table

GROUP BY id

The "another_column" can belong to the row holding the MIN() value or the MAX() value or even to another row not displayed at all. In other RDBMS than MySQL it's actually forbidden to select columns that do not use an aggregate function or are not listed in the GROUP BY clause, just to prevent that users make a mistake or think they got the right result.

So, in your case you seem to want to display the column "value" too. For above reasons, juergen_d's answer is wrong, because it doesn't select "value", and if it would, you can't be sure it's the right "value". Filipe Silva's answer is wrong, because it groups by "value". Doing this will in your case actually return the whole table. Romesh's answer is wrong, because using two times the MAX() function will get you the max values, obviously but not the value corresponding to the datetime value.

So, how do you have to do it? Here 3 ways are described. Learn them by applying them yourself. It's not that hard :)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值