mysql - update if exists otherwise insert -


this table structure shopping cart

enter image description here

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
enter image description here

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

if have these data group (1,38,1), new row inserted combination (1,38) not exist
enter image description here

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

Popular posts from this blog

java - Spring Data JPA: Why findOne(id) executing delete query internally? -

python - Mongodb How to add addtional information when aggregating? -

java - Incorrect order of records in M-M relationship in hibernate -