我从下表中选择唯一的 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