mysql查询显示最喜欢的帖子

时间:2018-08-30 10:51:26

标签: php mysql

我想从数据中计算一周内最喜欢的帖子。但是我的地雷很困惑,我该如何计算。我也只想显示一周内第一条最受欢迎的帖子。我搜索了示例答案,但未找到任何结果。请问你能帮帮我吗。该表如下所示,时间为unixtimestamp

+------------+------------+------------+------------+
|  post_id   | date       |  user_id   | post_id_fk |
+------------+-------------------------+------------+
|     32     | 1535624966 |   21       |   148      |
|     33     | 1535624990 |   68       |   148      |
|     34     | 1535625007 |   99       |   758      |
|     35     | 1535625022 |   12       |   148      |
|     36     | 1535625039 |   43       |   148      |
+------------+---------------------+----------------+

查询应使用日期unixtimestamp在一周内计数post_id_fk,并打印最喜欢的post_id_fk

我尝试了以下查询,但它只计算一行,但是我需要最受欢迎的post_id_fk,并且应该在一周内显示出来。

$query = mysqli_query($this->db,"SELECT 
COUNT(*) AS postLikeCount FROM post_like 
WHERE post_id_fk = post_id_fk") 
or die(mysqli_error($this->db));    
$row = mysqli_fetch_array($query, MYSQLI_ASSOC);  
return $row['postLikeCount'];

3 个答案:

答案 0 :(得分:2)

在MySQL 8之前的版本中,这是一个棘手的查询,因为您需要汇总两次;一次查找每个帖子和每周的计数,然后再次查找那些组中的最大计数。更令人困惑的是,我们还必须将UNIX时间戳转换为易于使用的日期格式。

SELECT
    t1.yearweek,
    t1.post_id_fk,
    t1.cnt AS max_count
FROM
(
    SELECT
        YEARWEEK(FROM_UNIXTIME(date)) AS yearweek,
        post_id_fk,
        COUNT(*) AS cnt
    FROM post_like
    GROUP BY
        YEARWEEK(FROM_UNIXTIME(date)),
        post_id_fk

) t1
INNER JOIN
(
    SELECT yearweek, MAX(cnt) AS max_cnt
    FROM
    (
        SELECT
            YEARWEEK(FROM_UNIXTIME(date)) AS yearweek,
            post_id_fk,
            COUNT(*) AS cnt
        FROM post_like
        GROUP BY
            YEARWEEK(FROM_UNIXTIME(date)),
            post_id_fk
    ) t
    GROUP BY yearweek
) t2
    ON t1.yearweek = t2.yearweek AND t1.cnt = t2.max_cnt;

enter image description here

Demo

答案 1 :(得分:1)

我知道这已经有了答案,但是此查询不满足您的要求吗?

SELECT COUNT(*) AS postLikeCount, date, post_id_fk 
FROM post_like
WHERE
    date BETWEEN FROM_UNIXTIME(UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 7 day))) 
    AND FROM_UNIXTIME(UNIX_TIMESTAMP) 
group by post_id_fk
order by postLikeCount DESC

答案 2 :(得分:0)

您必须按post_id SELECT COUNT(*) AS count FROM post_like WHERE /* here condition for week */ GROUP BY post_id SORT BY count DESC

对结果进行分组