mysql - update if exists otherwise insert -
this table structure shopping cart

i want insert row if new user_id , product_id combination not exist in table otherwise want update quantity if combination exists. intention update someone's shopping cart in database , insert if there new items.
for example, if have these data in table

if have these data group (1,23,5), update quantity in first row combination (1,23) exists

if have these data group (1,38,1), new row inserted combination (1,38) not exist
define unique index on values not want duplicated:
create unique index idx_shoppingcart_user_product on shoppingcart(userid, productid) then, duplicate of these two columns not allowed. (note: can define constraint using unique or primary key in create table.)
then use on duplicate key:
insert shoppingcart(user_id, product_id, quantity) select . . . on duplicate key update quantity = quantity + values(quantity); or, perhaps,
on duplicate key update quantity = values(quantity); your question vague on mean "update quantity only".
Comments
Post a Comment