MySQL: how to get x number of results per grouping [duplicate]

非 Y 不嫁゛ 提交于 2019-12-02 21:14:49

Try this query -

SELECT item_id, item_name, catid FROM 
  (SELECT t1.*, COUNT(*) cnt FROM items t1
    LEFT JOIN items t2
      ON t2.catid = t1.catid AND t2.item_id <= t1.item_id 
  GROUP BY
    t1.catid, t1.item_id
  ) t
WHERE
  cnt < 6
-- LIMIT 20

It will show first 5 items per category. Uncomment LIMIT 20 if you need. Join Categories table if you need.

SELECT item_id, item_name, catid
FROM (  SELECT item_id, item_name, catid,
            CASE WHEN @catid != catid THEN (@rownum := 1) + !(@catid := catid) ELSE @rownum := $rownum + 1 AS rownum
        FROM (  SELECT item_id, item_name, i.catid
                FROM items AS i
                INNER JOIN categories AS c
                ON i.catid = c.catid
                ORDER BY i.catid ASC) AS h, (SELECT @catid := NULL, @rownum := NULL) AS var
                HAVING rownum <= 5
                LIMIT 20) AS h2
ORDER BY item_id

Devart's solution looks right, but I have a bit of a pickle understanding it fully. Mine may not make much more sence to others, but it does to me.

EDIT: Understand Devart's solution now, and it is quite brilliant, actually. :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!