gpt4 book ai didi

php - 仅获取每个类别的随机项目

转载 作者:行者123 更新时间:2023-11-29 18:33:54 26 4
gpt4 key购买 nike

我有两个表、类别和项目,我想获得 10 个随机类别中每个类别的随机记录。

tb_category

category_id PK
category_name

tb_items

item_id PK
category_id FK

我的表 tb_category 大约有 40 行,tb_items 大约有 5k 行,我是搜索性能。

SELECT * FROM
( SELECT c.category_id as cid, c.category_name, i.item_id FROM
tb_category c INNER JOIN
tb_items i ON c.category_id = i.category_id ORDER BY RAND() ) AS ShuffeledItems
GROUP BY ShuffeledItems.cid limit 10

我不知道这是否是更好的方法。

谢谢。

最佳答案

我倾向于使用相关子查询:

select c.*,
(select i.item_id
from items i
where i.category_id = c.category_id
order by rand()
limit 1
) as item_id
from tb_category c
order by c.id
limit 10;

关于php - 仅获取每个类别的随机项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45473372/

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