gpt4 book ai didi

Mysql查询限制项数

转载 作者:行者123 更新时间:2023-11-29 21:09:45 26 4
gpt4 key购买 nike

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

最佳答案

利用组行数子查询的分配来尝试此解决方案。

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;

关于Mysql查询限制项数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36485031/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com