Sql 查询每个商店随机获得4种产品

Sql 查询每个商店随机获得4种产品,sql,postgresql,Sql,Postgresql,如果存在产品库存,我尝试为每个商店显示4个随机产品。我有3个表:一个用于商店信息—“ws_shop_official”,一个用于产品—“ws_product”,另一个用于存储产品图像信息—“ws_product_pic” 使用下面的语句,返回的结果是随机的,但是我没有得到每个商店返回的4个产品(行) select prod.product_id,prod.shop_id,prod.product_name,prod.normal_price,prod.stock,prod.create_time

如果存在产品库存,我尝试为每个商店显示4个随机产品。我有3个表:一个用于商店信息—“ws_shop_official”,一个用于产品—“ws_product”,另一个用于存储产品图像信息—“ws_product_pic”

使用下面的语句,返回的结果是随机的,但是我没有得到每个商店返回的4个产品(行)

select prod.product_id,prod.shop_id,prod.product_name,prod.normal_price,prod.stock,prod.create_time,prod.product_id,official.shop_id,img.file_name,img.file_path
from ws_product prod
join ws_shop_official official ON prod.shop_id = official.shop_id 
join ws_product_pic img ON prod.product_id = img.product_id 
where prod.stock > 0 AND prod.shop_id IN (select shop_id from ws_shop_official where status=1 )
order by prod.create_time DESC
有人对如何修复它有什么想法吗

预期的解决方案是每个商店4行产品信息。
对于每个店铺id,在循环中查询一次还是多次更好?

为此,我们使用PL/PgSQL,首先计算符合特定搜索条件的总行数:

    recnum := count(p.id) from
        stt_group g,
        stt_product p
    left join
        stt_image i
    on
        i.product = p.id
    and
        i.is_default = true
    and
        i.is_public = true
    where
        p.pgroup = g.id
    and
        g.id = group_id
    and
        p.online_shop = true;
然后我们计算所有记录对应于我们想要的行数的百分比,这在“size”变量中:

    percentage := 100.0 * size::numeric / recnum::numeric;
    if percentage > 100.0 then
        percentage = 100.0;
    end if;
最后,我们使用tablesample来计算所需的随机记录百分比:

    return query select
        p.id,
        p.name,
        p.price,
        p.stock_qty,
        p.stock_minqty,
        i.id,
        p.nr
    from
        stt_group g,
        stt_product p tablesample bernoulli(percentage)
    left join
        stt_image i
    on
        i.product = p.id
    and
        i.is_default = true
    and
        i.is_public = true
    where
        p.pgroup = g.id
    and
        g.id = group_id
    and
        p.online_shop = true
    order by
        p.name
    limit
        size;

虽然这是可行的,但请记住tablesample返回的是“大致”百分比,它可能多多少少,这就是我们限制返回行数的原因。

我们使用PostgreSQL 9.6,fwiw。您能否提供一些示例数据以及该示例数据的预期结果?