重新的标题:如何在MySQL中根据点赞数和时间相关性对表格进行排序?
P粉771233336
P粉771233336 2023-09-09 09:22:12
0
1
577

我有一个简单的问题,有两个mysql表,一个存储照片,另一个存储点赞。结构如下:

表 `photos` - id, name, image_id
表 `likes` - id_photos, timestamp

现在按照点赞数对照片进行排序并获取前3名很简单,可以使用以下查询语句:

SELECT photos.*
    , COUNT(likes.id) AS likes_count 
 FROM photos 
 LEFT JOIN likes ON photos.id = likes.id_photos 
 GROUP BY photos.id 
 ORDER BY likes_count DESC LIMIT 3;

但是我想要添加时间相关性,也就是说,新的点赞有更高的“权重”,即使某些照片有更多的点赞,但它们较旧,所以它们的排序低于点赞较少但较新的照片。

是否可能仅使用MySQL解决这个问题?还是需要在PHP中进行额外的处理?

P粉771233336
P粉771233336

全部回复(1)
P粉958986070

考虑一种情况,即 likestimestamp 是 UNIXTIME 字段,因此如果我们使用 SUM(timestamp) 而不是计算新的 likes 数量,将会给予更多的权重:

SELECT photos.*
    , COUNT(likes.id) AS likes_count 
    , SUM(likes.timestamp) AS likes_weight 
 FROM photos 
 LEFT JOIN likes ON photos.id = likes.id_photos 
 GROUP BY photos.id 
 ORDER BY likes_weight DESC LIMIT 3;

可以使用一些系数(例如 UNIX_TIMESTAMP())

SELECT photos.*
    , COUNT(likes.id) AS likes_count 
    , SUM(likes.timestamp)/UNIX_TIMESTAMP() AS likes_weight 
 FROM photos 
 LEFT JOIN likes ON photos.id = likes.id_photos 
 GROUP BY photos.id 
 ORDER BY likes_weight DESC LIMIT 3;
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板