MySQL Group By Consecutive Rows

后端 未结 2 1675
心在旅途
心在旅途 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:31

    Here's another version that works with MySQL Variables and doesn't require 3 level nesting deep. The first one pre-sorts the records in order by postID and Date and assigns them a sequential number per group whenever any time a value changes in one of the Post ID, Type and/or action. From that, Its a simple group by... no comparing record version T to T2 to T3... what if you wanted 4 or 5 criteria... would you have to nest even more entries?, or just add 2 more @sql variables to the comparison test...

    Your call on which is more efficient...

    select
          PreQuery.postID,
          PreQuery.PostType,
          PreQuery.Target,
          PreQuery.Action,
          PreQuery.Title,
          min( PreQuery.Date ) as FirstActionDate,
          max( PreQuery.Date ) as LastActionDate,
          count(*) as ActionEntries,
          group_concat( PreQuery.content ) as Content
       from
          ( select
                  t.*,
                  @lastSeq := if( t.action = @lastAction
                              AND t.postID = @lastPostID
                              AND t.postType = @lastPostType, @lastSeq, @lastSeq +1 ) as ActionSeq,
                  @lastAction := t.action,
                  @lastPostID := t.postID,
                  @lastPostType := t.PostType
               from
                  t,
                  ( select @lastAction := ' ',
                           @lastPostID := 0,
                           @lastPostType := ' ',
                           @lastSeq := 0 ) sqlVars
               order by
                  t.postid,
                  t.date ) PreQuery
       group by
          PreQuery.postID,
          PreQuery.ActionSeq,
          PreQuery.PostType,
          PreQuery.Action    
    

    Here's my link to SQLFiddle sample

    For the title, you might want to adjust the line...

    group_concat( distinct PreQuery.Title ) as Titles,

    At least this will give DISTINCT titles concatinated... much tougher to get let without nesting this entire query one more level by having the max query date and other elements to get the one title associated with that max date per all criteria.

提交回复
热议问题