2017-01-03 76 views
0

如果產品存貨存在,我試圖爲每個商店展示4個隨機產品。我有3個表格:一個用於商店信息 - 「ws_shop_official」,一個用於產品 - 「ws_product 「和一個存儲產品圖像信息 - 」ws_product_pic「。查詢獲得每個商店隨機4個產品

使用下面的語句,返回的結果是隨機的,但我沒有得到每個商店返回的完全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,在循環中查詢一次或多次也更好嗎?

+0

您能否提供一些樣本數據和該樣本數據的預期結果? – Viki888

回答

0

我們使用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; 

然後我們計算的所有記錄多少百分比對應的行數,我們希望,這對我們在「大小」變量:

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會「粗略」返回百分比,可能會多少少一些,這就是我們限制返回行數的原因。

+0

我們使用PostgreSQL 9.6,fwiw。 –

相關問題