简体   繁体   English

MySQL从多个获取最后的日期记录

[英]MySQL get last date records from multiple

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: 我想得到每个ID和类型记录的最后日期:

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. 可以使用GROUP BY ,但了解其工作原理非常重要。

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. 当您使用GROUP BY一组行折叠为一个,并且在GROUP BY子句中未使用的其他列中显示的内容将通过使用聚合函数确定,或者它是该组中的随机行。 You can't be sure to get the row corresponding to the row displayed holding the MAX() value or whatever aggregate function you used. 您不能确定获取与显示的行对应的行,其中包含MAX()值或您使用的任何聚合函数。 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. “another_column”可以属于包含MIN()值或MAX()值的行,甚至可以属于根本不显示的另一行。 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. 在除MySQL之外的其他RDBMS中,实际上禁止选择不使用聚合函数或未在GROUP BY子句中列出的列,只是为了防止用户犯错误或认为他们得到了正确的结果。

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". 由于上述原因,juergen_d的答案是错误的,因为它没有选择“值”,如果可以的话,你不能确定它是正确的“价值”。 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. Romesh的答案是错误的,因为使用两次MAX()函数会得到最大值,显然不是与datetime值对应的值。

So, how do you have to do it? 那么,你怎么做呢? Here 3 ways are described . 这里描述了3种方式 Learn them by applying them yourself. 通过自己应用它们来学习它们。 It's not that hard :) 这不是很难:)

select id, type, max(datetime)
from your_table
group by id, type

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM