【问题标题】:Popular Items in MysqlMysql中的热门项目
【发布时间】:2013-03-14 04:48:47
【问题描述】:

我有两个表,我想使用它们来确定 stream_post 的“受欢迎程度”。 Stream_Post_Comment 和 Stream_Post_Like。

stream_post_comment_id  stream_post_id  user_id
1                             1            1        
2                             2            1        
3                             2            4        
4                             2            1    



stream_post_like_id stream_post_id  user_id
1                           1           1   
2                           2           3   
3                           3           2   
4                           3           1   

我无法将一个查询概念化,该查询会输出如下内容:

stream_post_id popularity
      1            1
      2            3 
      3            2

user_id 在给定帖子的流行度得分中只计入一次。例如,如果他们评论并喜欢某个帖子,他们只会算作“1”人气得分。

【问题讨论】:

    标签: mysql sql select sum


    【解决方案1】:

    试试这个:

    SELECT
      stream_post_id,
      COUNT(DISTINCT user_id) AS popularity
    FROM
    (
       SELECT stream_post_id, user_id
       FROM stream_post_comment
       UNION ALL
       SELECT stream_post_id, user_id
       FROM stream_post_like
    ) AS sub
    GROUP BY stream_post_id;
    

    SQL Fiddle Demo

    这会给你:

    | STREAM_POST_ID | POPULARITY |
    -------------------------------
    |              1 |          1 |
    |              2 |          3 |
    |              3 |          2 |
    

    【讨论】:

      【解决方案2】:

      似乎这应该是存储的东西,并在触发评论或喜欢时更新。

      您可以编写一个 PHP 脚本来计算和填充“流行度”字段,然后使用触发器在每次发生新情况时更新计数 - 这将在其中进行检查以确保它没有如果用户已经点过赞或评论,则不要增加它。

      【讨论】:

        【解决方案3】:

        试试这个查询

        SELECT 
              stream_post_id, 
              count(user_id) AS 'popularity'
        FROM 
               (SELECT 
                      stream_post_id, 
                      user_id 
               FROM 
                      Stream_Post_Comment 
               UNION
               SELECT 
                      stream_post_id, 
                      user_id 
               FROM 
                      Stream_Post_Like) tbl
        GROUP BY 
               stream_post_id
        

        希望对你有帮助

        【讨论】:

          猜你喜欢
          • 2014-10-17
          • 1970-01-01
          • 1970-01-01
          • 2022-08-23
          • 1970-01-01
          • 2020-11-28
          • 2018-04-18
          • 2013-11-14
          • 1970-01-01
          相关资源
          最近更新 更多