I have a feed application that I am trying to group results from consecutively. My table looks like this:
postid | posttype | target | action |
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 highestdate
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.