简体   繁体   English

如何检索每个组中的最后一条记录

[英]How to retrieve the last record in each group

I am trying to get data from my table using group by . 我正在尝试使用group by从我的表中获取数据。 using group by works correctly but i need to take only last inserted item of every group but its not work. 使用group by工作正常但我需要只采取每个组的最后插入项目,但它不起作用。 my query always return first item of each group. 我的查询总是返回每个组的第一项。

my query 我的查询

SELECT id,type,userId,performDate,eventId FROM
`user_marker` where  `eventId`='842' and DATE_FORMAT(from_unixtime(performDate),'%Y%c%d')
=DATE_FORMAT(now(),'%Y%c%d') 
 and `visibility`='1'GROUP BY type ORDER BY id DESC

Please try 请试试

SELECT a.* FROM ( SELECT id,type,userId,performDate,eventId FROM 
`user_marker` where  `eventId`='842' and DATE_FORMAT(from_unixtime(performDate),'%Y%c%d')
=DATE_FORMAT(now(),'%Y%c%d') and `visibility`='1' ORDER BY id DESC ) as a GROUP BY a.type 

You can try as per below- 您可以按以下方式尝试 -

SELECT b.id,b.type,b.userId,b.performDate,b.eventId 
FROM user_marker b 
JOIN (SELECT `type`,MAX(performDate) 
FROM user_marker 
WHERE  `eventId`='842' AND DATE(FROM_UNIXTIME(performDate))=CURDATE() AND `visibility`='1' 
GROUP BY `type`) a ON a.type=b.type AND a.performDate=b.performDate 
ORDER BY b.`type`;

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

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