php - MySQL Query: insert if entry is duplicate otherwise update the existing row values -
i have table called bag(again):
+--------+----------+---------+----------+ | bag_id | chara_id | item_id | item_qty | +--------+----------+---------+----------+ | 1 | 1 | 2 | 22 | | 2 | 1 | 1 | 55 | | 3 | 3 | 1 | 2 | | 6 | 3 | 4 | 2 | | 7 | 4 | 4 | 2 | | 8 | 5 | 4 | 2 | | 9 | 6 | 4 | 2 | | 10 | 1 | 5 | 1 | | 14 | 1 | 8 | 1 | | 15 | 1 | 6 | 1 | | 18 | 1 | 4 | 1 | | 19 | 1 | 3 | 1 | | 29 | 8 | 1 | 1 | | 30 | 8 | 7 | 1 | | 33 | 6 | 2 | 1 | +--------+----------+---------+----------+
and have sql statement:
insert bag(bag_id, chara_id, item_id, item_qty)values(null, :id, :item_id,1)
after asking how delete duplicates
wat want next(to further restrict duplicates)is when user buys item existing in bag increase item_qty 1 instead.
like:
if chara_id = exist , item_id exist item_qty = item_qty + 1 else #..normal insert
if use:
insert bag(bag_id, chara_id, item_id)values(null, 1, 2)
it should not insert update item_qty 23 because entry existing.
mysql supports insert ... on duplicate key update
but before work, need have unique constraint on table. if don't have unique constraint yet, based on example checking on 2 columns if values exists,
alter table bag add constraint tb_unique unique (chara_id, item_id)
once has been implemented, on duplicate key update
not work.
insert bag(chara_id, item_id, item_qty) values(1, 2, 1) on duplicate key update item_qty = item_qty + 1
Comments
Post a Comment