1

i have a 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 i have this SQL Statement:

INSERT INTO bag(bag_id, chara_id, item_id, item_qty)VALUES(NULL, :id, :item_id,1)

after asking how to delete duplicates
wat i want to do next(to further restrict duplicates)is when a user buys an item already existing in his bag it increase the item_qty by 1 instead.

like:

if chara_id = exist and item_id exist 
   item_qty = item_qty + 1
else
   #..normal insert

if i use:

INSERT INTO bag(bag_id, chara_id, item_id)VALUES(NULL, 1, 2)

it should not insert but update the item_qty to 23 because that entry is already existing.

2 Answers 2

3

INSERT ... ON DUPLICATE KEY UPDATE

http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

Sign up to request clarification or add additional context in comments.

3 Comments

ive read it, used it but it seems to be just inserting not updating even if an entry is existing
then you need to set a unique key on the combination of chara_id and item_id
wait,.. how do i do that i only know how to set a unique undex.
2

MySQL supports INSERT ... ON DUPLICATE KEY UPDATE

but before it will work, you need to have an unique constraint on the table. If you don't have a unique constraint yet, based on your example you are checking on two columns if the values already exists,

ALTER TABLE bag ADD CONSTRAINT tb_unique UNIQUE (chara_id, item_id)

Once it has been implemented, ON DUPLICATE KEY UPDATE will not work.

INSERT INTO bag(chara_id, item_id, item_qty)
VALUES(1, 2, 1)
ON DUPLICATE KEY UPDATE item_qty = item_qty + 1

2 Comments

i have just done that a while ago, and it seems to be working fine :) thanks again, i am confused though why mysql is returning 2 rows inserted. : )
I am also seeing "2 rows inserted" but it seems that only one row is actually being inserted. Is this a phpMyAdmin bug? using 4.4.12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.