我有两个表:集合和 collection_items 。
我正在试图弄清楚如何为每个集合选择,在同一个查询中最多可以获得4个collection_items。
某些馆藏可能有超过4件商品,但我只需要最多4件商品。
以下查询返回每个集合的所有项目,但不知道如何将其限制为4。
SELECT cn.*, o.url_thumb
FROM collection_names as cn LEFT JOIN collection_items as ci ON ci.collection_id=cn.id
LEFT JOIN objects as o ON o.ID=ci.object_id
WHERE cn.public=1
ORDER BY cn.fecha DESC
LIMIT 0, 20
答案 0 :(得分:0)
使用group row num
和sub-query
的分配来尝试此解决方案。
select id, user_id, image_object_id, name, public, description, fecha, url_thumb
from
(
select
*,
IF(id = @last_id, @grp_rn := @grp_rn + 1, @grp_rn := 1) as grp_rn
from
(
SELECT cn.*, o.url_thumb
FROM collection_names as cn LEFT JOIN collection_items as ci ON ci.collection_id=cn.id
LEFT JOIN objects as o ON o.ID=ci.object_id
WHERE cn.public=1
ORDER BY cn.fecha DESC
LIMIT 0, 20
) as t cross join (select @grp_rn := 0, @last_id := NULL) param
order by t.id
) as t2
where t2.grp_rn <=4;