Mysql查询限制项目数

时间:2016-04-07 19:05:36

标签: mysql

我有两个表:集合 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

表定义: enter image description here

1 个答案:

答案 0 :(得分:0)

使用group row numsub-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;