开发者

Insert select ON DUPLICATE KEY question

开发者 https://www.devze.com 2023-01-28 12:26 出处:网络
I asked this question yesterday: Insert select with a twist question Now i have the problem that i want the data to update itself if it is a duplicate row.

I asked this question yesterday:

Insert select with a twist question


Now i have the problem that i want the data to update itself if it is a duplicate row.

So i found that i could do it by doing this:

insert into product_quantity 
(groupId, productId, quantity) 
select 3, productId, quantity 
from product_quantity 
ON DUPLICATE KEY UPDATE    
product_quantity.quantity = VALUES(product_quantity.quantity);

But i want the quantity to update itself by adding the quantity to the already existsing qua开发者_StackOverflow社区ntity.

So i want something like this:

ON DUPLICATE KEY UPDATE    
product_quantity.quantity = 
  VALUES(product_quantity.quantity) + product_quantity.quantity;

So if i got:

     id----groupId----productId----quantity
     1 ----- 2 ------------2--------------5
     2 ----- 3 ------------2--------------5

Where groupId and productId are unique.

And i do the Insert-select-duplicate query:

insert into product_quantity 
(groupId, productId, quantity) 
select 3, 2, 5
from product_quantity 
ON DUPLICATE KEY UPDATE    
product_quantity.quantity = VALUES(product_quantity.quantity) + *OLD QUANTITY*;

MySql should add the quantity on row 1 to row 2, so it would look like this:

     id----groupId----productId----quantity
     1 ----- 2 ------------2--------------5
     2 ----- 3 ------------2--------------10

Anyone got an idea if this is possible?


   INSERT 
     INTO product_quantity (groupId, productId, quantity) 
   VALUES (3, productId, quantity) 
     FROM product_quantity  
       ON DUPLICATE KEY 
   UPDATE quantity = 5 + VALUES(quantity); 

I think this'll do what you need.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号