[英]sql get row with max date and relative id record
I try to make a simple query, spent on it a tone of hours and get nothing.... 我尝试做一个简单的查询,花了几个小时的时间,什么都没得到....
All I need is to get MAX date and all is corresponding fields. 我只需要获得MAX日期,所有都是相应的字段。
I'm explain: I have a table with this fields: BasketID
, OrderStatusTypeID
, StatusDate
. 我解释说:我有一个包含这些字段的表:
BasketID
, OrderStatusTypeID
, StatusDate
。
I try to get only one record that contain OrderStatusTypeID
value with the last StatusDate
. 我尝试只获得一个包含
OrderStatusTypeID
值的记录和最后一个StatusDate
。
This is the data 这是数据
BasketID OrderStatusTypeID date
1111 13 2013-04-01 11:38:31
1111 26 2013-04-04 17:44:17
1111 39 2013-04-02 12:35:07
1111 40 2013-04-08 12:52:55
This is my query: 这是我的查询:
SELECT BasketID, OrderStatusTypeID, max(StatusDate) date
FROM st
where BasketID=1111
group by BasketID
This is the results i need 这是我需要的结果
BasketID OrderStatusTypeID date
63558 40 2013-04-08 12:52:55
For some reason I only get OrderStatusTypeID = 13
and not 40
! 出于某种原因,我只获得
OrderStatusTypeID = 13
而不是40
! (max of StatusDate, and NOT max of OrderStatusTypeID). (StatusDate的最大值,而不是OrderStatusTypeID的最大值)。
Why??? 为什么???
BasketID OrderStatusTypeID date
63558 13 2013-04-08 12:52:55
Thanks for fast response! 感谢您的快速反应!
I assume you are using MySQL
because you can run the query even if you have not specified all the non-aggregate column in the GROUP BY
clause. 我假设您使用的是
MySQL
因为即使您没有在GROUP BY
子句中指定所有非聚合列,也可以运行查询。
There are many ways to solve the problem but I'm used to do it this way. 有很多方法可以解决这个问题,但我习惯这样做。 The query uses a subquery which separately gets the latest
date
for every BasketID
. 该查询使用子查询,该子查询分别获取每个
BasketID
的最新date
。 Since the subquery returned only two columns, you need to join it back on the table itself to get the other columns provided that it match on two columns: BasketID
, Date
. 由于子查询只返回两列,因此需要将其连接回表本身以获得其他列,只要它在两列上匹配:
BasketID
, Date
。
SELECT a.*
FROM st a
INNER JOIN
(
SELECT BasketID, MAX(Date) max_date
FROM st
GROUP BY BasketID
) b ON a.BasketID = b.BasketID AND
a.Date = b.max_date
Your query has executed successfully without throwing an exception even though there are non-aggregate columns that are not specified in the GROUP BY
clause because it is permitted in MySQL. 即使存在未在
GROUP BY
子句中指定的非聚合列,您的查询也已成功执行而不会抛出异常,因为它在MySQL中是允许的。 See MySQL Extensions to GROUP BY . 请参阅GROUP BY的MySQL扩展 。
I know this is an old thread, but why isn't it possible to use ORDER BY and LIMIT in this case? 我知道这是一个旧线程,但为什么在这种情况下不可能使用ORDER BY和LIMIT? A query like that:
像这样的查询:
SELECT * FROM st WHERE BasketID=1111 ORDER BY Date DESC LIMIT 1 SELECT * FROM st WHERE BasketID = 1111 ORDER BY Date DESC LIMIT 1
Its pretty easy to use TOP command like: 它非常容易使用TOP命令,如:
SELECT TOP 1 * FROM st
WHERE BasketID = 1111
ORDER BY date DESC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.