简体   繁体   English

使用GROUP BY和ORDER BY时间戳DESC进行MySQL查询

[英]MySQL query with GROUP BY and ORDER BY timestamp DESC

I am saving the history of Facebook likes for a page, identified by user_id . 我正在保存Facebook喜欢的页面历史记录,由user_id标识。

Now from this table, I need to get a set representing the user_id's and their latest number of likes, based on the most recent timestamp . 现在从这个表中,我需要根据最新的timestamp得到一个表示user_id及其最新喜欢的集合。

I started off with this: 我从这开始:

SELECT * 
FROM facebook_log 
GROUP BY user_id 
ORDER BY timestamp DESC;

But that does not do what I want because it returns the first records with the lowest timestamps . 但这并不是我想要的,因为它返回timestamps最低的第一个记录。

I read something online about GROUP returning the very first records from the table. 我在网上读到了一些关于GROUP从表中返回第一条记录的内容。

I also understood something about JOIN the table with itself, but that doesn't work either, or I did something wrong. 我也理解了一些关于JOIN桌子的事情,但这也不起作用,或者我做错了什么。

If you just need the user_id and the timestamp, you can just do 如果您只需要user_id和时间戳,那么您可以这样做

select f.user_id, max(f.timestamp)
from facebook_log
group by user_id;

if you need all the data from the table, you can do 如果您需要表格中的所有数据,您可以这样做

select f.*
from facebook_log f
inner join (select max(timestamp) mt, user_id
            from facebook_log 
            group by user_id) m
on m.user_id = f.user_id and m.mt = f.timestamp

You can also get the latest number of likes by using this MySQL trick: 您还可以通过使用此MySQL技巧获得最新数量的喜欢:

select f.user_id, max(f.timestamp),
       substring_index(group_concat(f.numlikes order by f.timestamp desc), ',', 1) as LatestLikes
from facebook_log f
group by f.user_id;

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

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