MySQL Query: insert if entry is duplicate otherwise update the existing row values

风流意气都作罢 提交于 2019-12-24 09:03:18

问题


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.


回答1:


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
  • INSERT ... ON DUPLICATE KEY UPDATE



回答2:


INSERT ... ON DUPLICATE KEY UPDATE

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



来源:https://stackoverflow.com/questions/16351292/mysql-query-insert-if-entry-is-duplicate-otherwise-update-the-existing-row-valu

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!