2010-12-03 8 views
0

ich diese Frage gestern:Insert ON DUPLICATE KEY Frage wählen fragte

Insert select with a twist question


Jetzt habe ich das Problem, dass ich die Daten wollen selbst zu aktualisieren, wenn es sich um eine doppelte Zeile ist. So fand
ich, dass ich es dies tun, tun könnte:

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); 

Aber ich möchte, dass die Menge selbst zu aktualisieren, indem Sie die Menge auf die bereits existsing Menge hinzugefügt wird.

Deshalb möchte ich etwas wie folgt aus:

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

Also, wenn ich erhielt:

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

Wo groupId und productId einzigartig sind.

Und ich tun, um die Insert-select-Duplikat-Abfrage:

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 die Menge auf Zeile 1 hinzufügen sollten 2 bis Zeile, also würde es so aussehen:

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

Jeder bekam eine Idee, wenn das möglich ist?

Antwort

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

Ich denke, das wird tun, was Sie brauchen.

Verwandte Themen