我有一个包含id、标题、时间戳和category_id列名的MySQL数据库(博客)。如何从每个具有最新时间戳的类别中选择一行?如果我有3行属于类别1,2,1,那么我将返回两行,其中"1“中类别的最高时间戳是第一行,而类别为"2”的行是第二行。
我试过了:
SELECT title, timestamp, category_id
FROM blogs
WHERE timestamp IN (
SELECT MAX(timestamp)
FROM blogs
GROUP BY category_id
)但是由于timestamp不是惟一的,所以它可以额外引入一个category_id =1的行,该行的时间戳与在内部select语句中选择的category_id =2的行的时间戳相同。
发布于 2016-03-17 00:47:06
你也可以试试这种方式。当我在MySQL5.6中尝试时,它对我来说是有效的。它返回两个具有最高时间戳和category_id升序的类别。
SELECT title,timestamp,category_id from blogs WHERE timestamp in (select max( timestamp ) FROM blogs group by category_id) group by timestamp,category_id order by category_id asc;
https://stackoverflow.com/questions/11783072
复制相似问题