Intelligent MySQL GROUP BY for Activity Streams

前端 未结 4 987
长发绾君心
长发绾君心 2020-12-13 18:52

I\'m building an activity stream for our site, and have made some decent headway with something that works pretty well.

It\'s powered by two tables:

4条回答
  •  半阙折子戏
    2020-12-13 19:27

    My impression is you need to group by user, as you do, but also, after that grouping, by action.

    It looks to me like you need a subquery like this:

    SELECT *, -- or whatever columns
       SUM(actions_in_group) AS total_rows_in_group,
       GROUP_CONCAT(in_collection) AS complete_collection
       FROM
         ( SELECT stream.*, -- or whatever columns
              COUNT(stream.id) AS actions_in_user_group,
              GROUP_CONCAT(stream.id) AS actions_in_user_collection
           FROM stream
           INNER JOIN follows
           ON stream.user_id = follows.following_user
           WHERE follows.user_id = '1'
             AND stream.hidden = '0'
           GROUP BY stream.user_id,
                date(stream.stream_date)
         )
       GROUP BY object_id,
                date(stream.stream_date)
       ORDER BY stream.stream_date DESC;
    

    Your initial query (now the inner one) groups by user, but then the user groups are regrouped by identical actions - that is, identical products bought or sales from one seller would be put together.

提交回复
热议问题