performance of mysql query result using max, group by, temporary table and random row selection -


i selecting unique productid w.r.t sizeid below table, need select random row when prices same.

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 

i expecting below result if price same, result random aff_id(4 or 1 in above example).

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

below query results same above. respect performance using temporary table.

select * (    select ap1.aff_id,ap1.wl_product_id,ap1.wl_size_id, ap1.price,(ap1.price*rand())as random_number     affiliate_product ap1    inner join     (select wl_product_id, max(price) price affiliate_product  wl_product_id>0 group wl_product_id,wl_size_id) ap2    on (ap1.wl_product_id = ap2.wl_product_id , ap1.price = ap2.price) order wl_product_id,random_number )as temp_tbl group wl_product_id,wl_size_id 

you can group_concat() , substring_index():

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

one note: convert aff_id character representation. if using join's afterwards, might want convert number.

edit:

to information max price, use join information:

select t.* (select wl_product_id, wl_size_id, price,              substring_index(group_concat(aff_id order rand()), ',', 1) aff_id       t       group wl_product_id, wl_size_id, price      ) t join      (select wl_product_id, wl_size_id, max(price) maxprice       t       group wl_product_id, wl_size_id      ) tmax       on tmax.wl_product_id = t.wl_product_id ,          tmax.wl_size_id = t.wl_size_id  ,          tmax.maxprice = t.price; 

Comments