Pregunta

I have the following sample table data:

id, price, product_id, default
905928, 2.92, 1523, 0
905929, 2.89, 1523, 0
905930, 3.92, 1524, 0
905931, 6.67, 1525, 0
905932, 11.92, 1526, 0
905933, 5.34, 1526, 0
905934, 3.92, 1527, 0
905935, 1.11, 1528, 0

I would like to update the default column with a 1, whenever the lowest priced item within a duplicate product id group is flagged. So the result should look like:

id, price, product_id, default
905928, 2.92, 1523, 0
905929, 2.89, 1523, 1
905930, 3.92, 1524, 1
905931, 6.67, 1525, 1
905932, 11.92, 1526, 0
905933, 5.34, 1526, 1
905934, 3.92, 1527, 1
905935, 1.11, 1528, 0
905936, 0.11, 1528, 1
905937, 1.89, 1528, 0

Thanks in advance.

¿Fue útil?

Solución

Try this:

update yourtable a
inner join
(select product_id, min(price) minprice from
 yourtable 
 group by product_id
) b
on a.product_id = b.product_id
inner join 
(select product_id, price, min(id) minid from
 yourtable
 group by product_id, price
) c
on a.product_id = c.product_id and c.price = b.minprice
set defaultvalue = 1
where a.price = b.minprice
and a.id = c.minid

Demo here.

The second join is used to get the minimum value of id for the case where multiple records have lowest price for same product_id.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top