MySQL分组排序问题

时间:2016-08-04 21:02:03

标签: mysql database sorting grouping

我有一张用户观看历史记录表。我记录了' content_id',' user_id'并在名为' watch_history'的表格中添加时间戳。每次查看内容。即使连续多次观看相同的内容,也会记录每次点击。

我需要提取观看记录,但是' content_id'列应该是不同的,并按照最近观看的顺序排序...我发现很难解释,但基本上确切地说YouTube观看历史记录的工作原理(没有同一视频的多个实例)。

这是我到目前为止所做的:

SELECT content_id, time_stamp, user_id, 
     COUNT(DISTINCT content_id) AS hit_count 
FROM watch_history 
WHERE user_id = X 
GROUP BY content_id 
ORDER BY time_stamp DESC

它有效,但我需要' time_stamp'字段反映最后一次观看内容,有什么帮助吗?

感谢。

2 个答案:

答案 0 :(得分:3)

SELECT中的列不在GROUP BY中。这对于user_id来说是可以接受的,因为它是固定值。但对timestamp来说,这不行。

使用MAX()聚合功能:

SELECT content_id, MAX(time_stamp) as time_stamp, user_id, 
       COUNT(*) AS hit_count 
FROM watch_history 
WHERE user_id = X 
GROUP BY content_id, user_id
ORDER BY MAX(time_stamp) DESC;

注意:COUNT(DISTINCT content_id)没有意义。它将在每一行返回“1”(除非有content_idNULL的行)。我想你只想要COUNT(*)

答案 1 :(得分:0)

您希望按最新内容视图排序匹配,还是按特定查看者对内容的最新视图进行排序?

如果答案是前者,那么:

SELECT content_id, user_id, 
     COUNT(content_id) AS hit_count 
FROM watch_history h
WHERE user_id = X 
GROUP BY content_id
ORDER BY (Select Max(timestamp) from watch_history 
          Where user_id = X 
             and content_id = h.content_id) DESC

SELECT content_id, time_stamp, user_id, 
     COUNT(content_id) AS hit_count 
FROM watch_history h
   join watch_history last
       on last.content_id = h.Content_id
          and last.timestamp = 
              (Select max(timestamp) FROM watch_history 
               where user_id = X 
                  and content_id = h.content_id)
WHERE user_id = X 
GROUP BY content_id, time_stamp
ORDER BY last.timestamp desc