可能重复:
mysql: Using LIMIT within GROUP BY to get N results per group?
我有两张桌子:
每个项目属于一个类别。我想要做的是每个类别选择5个项目,但总共说20个项目。
SELECT
item_id, item_name, items.catid
FROM
items, categories
WHERE
items.catid = categories.catid
GROUP BY items.catid LIMIT 0,5 //5 per category group
编辑:如果每个类别有超过5个项目 - 它们应按item_id(数值)排序
答案 0 :(得分:5)
尝试此查询 -
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
每个类别会显示前5个项目。如果需要,请取消注释LIMIT 20
。如果需要,请加入Categories
表。
答案 1 :(得分:0)
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的解决方案看起来是正确的,但我对它有一点了解。我可能不会对别人有太多的了解,但这对我有用。
编辑:现在了解Devart的解决方案,实际上它非常出色。 :)