根据现有列值插入新列

时间:2014-11-29 02:05:14

标签: mysql insert

我在mysql中有一个表table1,如下所示:

price        item     count
100          xyz      5
200          xyz      1
300          xyz      4
400          abc      1
500          abc      2

我想插入一个新列' new_price'这将保持价格'对于那个'项目'最高的'计数。所以新表将是

price        item     count     new_price
100          xyz      5         100
200          xyz      1         100
300          xyz      4         100
400          abc      1         500
500          abc      2         500

最有效的方法是什么?非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我认为最简单的方法是使用变量:

  select t.*,
         (@price := if(@i = item, @price,
                       if(@i := item, price, price)
                      )
         ) as new_price
  from table1 t cross join
       (select @i := '', @price := -1) vars
  order by item, count desc;

如果您确实想要更新表格中的值,您也可以将其纳入update

update table1 t join
       (select t.*,
               (@price := if(@i = item, @price,
                             if(@i := item, price, price)
                            )
               ) as new_price
        from table1 t cross join
             (select @i := '', @price := -1) vars
        order by item, count desc
       ) tp
       on tp.item = t.item and tp.price = t.price and tp.count = t.count
    set t.new_price = tp.price;