MySQL Group By Consecutive Rows

后端 未结 2 1607
心在旅途
心在旅途 2021-01-06 17:09

I have a feed application that I am trying to group results from consecutively. My table looks like this:

    postid | posttype | target | action     |              


        
2条回答
  •  广开言路
    2021-01-06 17:33

    There is no primary key in your table so for my example I used date. You should create an auto increment value and use that instead of the date in my example.

    This is a solution (view on SQL Fiddle):

    SELECT 
      postid,
      posttype,
      target,
      action,
      COALESCE((
        SELECT date
        FROM t t2
        WHERE t2.postid = t.postid
        AND t2.posttype = t.posttype
        AND t2.action = t.action
        AND t2.date > t.date
        AND NOT EXISTS (
          SELECT TRUE
          FROM t t3
          WHERE t3.date > t.date
          AND t3.date < t2.date
          AND (t3.postid != t.postid OR t3.posttype != t.posttype OR t3.action != t.action)
        )
      ), t.date) AS group_criterion,
      MAX(title),
      GROUP_CONCAT(content)
    FROM t
    GROUP BY 1,2,3,4,5
    ORDER BY group_criterion
    

    It basically reads:

    For each row create a group criterion and in the end group by it.
    This criterion is the highest date of the rows following the current one and having the same postid, posttype and action as the current one but there may be not a row of different postid, posttype or action between them.
    In other words, the group criterion is the highest occurring date in a group of consecutive entries.

    If you use proper indexes it shouldn't be terribly slow but if you have a lot of rows you should think of caching this information.

提交回复
热议问题