Skip to content Skip to sidebar Skip to footer

Greatest N-per-group With Multiple Joins

Evening, I am trying to get an output of rows that are limited to n per group in MySQL. I can get it to work without joins, but with it I am just shy. I've pasted a dump of the rel

Solution 1:

This works:

SET @num := 1, @prevCat := 0;
SELECT title, start, end, type, description, linkOut, outType, catRef, row_number
FROM (
SELECT title, start, end, type, description, linkOut, outType, catRef,
@num := if(@prevCat = catRef, @num + 1, 1) as row_number,
@prevCat AS tog,
@prevCat := catRef AS dummy
FROM (
    SELECT title, start, end, resources.type, description, linkOut, outType, catRef
    FROM resources LEFT JOIN placesRel ON placesRel.refId = resId LEFT JOIN catRel ON catRel.refId = resId
    WHERE status = 'live' AND placesRel.type = 'res' AND catRel.type = 'res'
    ORDER BY catRef
) AS w
) AS x WHERE x.row_number <= 4;

You need to put your joined query in a sub-query and order it by the column you want to group by. Use it's parent query to add row numbers. Then, the top-level query glues it all together.

If you don't put your joined query in it's own sub-query, the results won't be ordered as you wish, but instead will come out in the order they are in the database. This means the data is not grouped, so row numbers will no be applied to ordered rows.


Post a Comment for "Greatest N-per-group With Multiple Joins"