MYSQL根据最低值选择Update Distinct Column

时间:2014-05-06 00:06:59

标签: join distinct

我有以下样本表数据:

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

每当标记重复产品ID组中的最低价格商品时,我想用1更新默认列。所以结果应该是这样的:

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

提前致谢。

1 个答案:

答案 0 :(得分:0)

试试这个:

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

演示here

第二个join用于获取id的最小值,以用于多个记录对同一price的{​​{1}}个product_id最低的情况。