2

我从下表中选择唯一的 productid wrt sizeid,但是当价格相同时我需要选择随机行。

aff_id,  wl_product_id, wl_size_id,  price
1           40             10        57
3           41             11        65
4           41             11        67
1           41             11        67

如果价格相同,我期待以下结果,将导致随机 aff_id(在上面的示例中为 4 或 1)。

 aff_id,  wl_product_id, wl_size_id,  price,   random_number
    1           40         10        57        37.5708656809953
    4(random)   41         11        67        88.2194444427453

下面的查询结果与上面相同。但在性能方面很好,因为我使用的是临时表。

SELECT * FROM (
   SELECT ap1.aff_id,ap1.wl_product_id,ap1.wl_size_id, ap1.price,(ap1.price*RAND())AS random_number 
   FROM affiliate_product ap1
   INNER JOIN 
   (SELECT wl_product_id, MAX(price) AS price FROM affiliate_product  WHERE wl_product_id>0 GROUP BY wl_product_id,wl_size_id) ap2
   ON (ap1.wl_product_id = ap2.wl_product_id AND ap1.price = ap2.price) ORDER BY wl_product_id,random_number
)AS temp_tbl GROUP BY wl_product_id,wl_size_id
4

1 回答 1

1

你可以用group_concat()and做到这一点substring_index()

select wl_product_id, wl_size_id, price,
       substring_index(group_concat(aff_id order by rand()), ',', 1) as aff_id
from t
group by wl_product_id, wl_size_id, price;

注意:这会将 转换aff_id为字符表示。如果您之后使用 for join,那么您可能希望将其转换回数字。

编辑:

要获取最高价格的信息,请使用 ajoin获取该信息:

select t.*
from (select wl_product_id, wl_size_id, price,
             substring_index(group_concat(aff_id order by rand()), ',', 1) as aff_id
      from t
      group by wl_product_id, wl_size_id, price
     ) t join
     (select wl_product_id, wl_size_id, max(price) as maxprice
      from t
      group by wl_product_id, wl_size_id
     ) tmax
      on tmax.wl_product_id = t.wl_product_id and
         tmax.wl_size_id = t.wl_size_id  and
         tmax.maxprice = t.price;
于 2013-07-19T11:05:15.760 回答