我有一张名为库存的表格 chara_id,item_id和item_level 是一个唯一约束
+--------------+----------+---------+------------+----------+
| inventory_id | chara_id | item_id | item_level | item_qty |
+--------------+----------+---------+------------+----------+
| 35 | 1 | 2 | 0 | 3 |
| 37 | 1 | 14 | 0 | 1 |
| 46 | 4 | 4 | 0 | 1 |
| 49 | 1 | 3 | 0 | 1 |
| 66 | 16 | 6 | 0 | 1 |
| 67 | 16 | 1 | 0 | 1 |
| 75 | 17 | 3 | 0 | 1 |
| 78 | 15 | 2 | 0 | 1 |
| 86 | 12 | 3 | 0 | 2 |
| 88 | 12 | 1 | 0 | 1 |
+--------------+----------+---------+------------+----------+
我有第二个名为设备
的表格+----------+----------+-----------+-------------+----------+---------+--------------+----------------+-------------+------------+
| equip_id | chara_id | weapon_id | headgear_id | armor_id | ring_id | weapon_level | headgear_level | armor_level | ring_level |
+----------+----------+-----------+-------------+----------+---------+--------------+----------------+-------------+------------+
| 1 | 1 | 2 | 16 | 18 | 17 | 0 | 0 | 0 | 0 |
| 2 | 2 | 2 | 5 | 6 | 0 | 0 | 0 | 0 | 0 |
| 3 | 3 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 4 | 4 | 2 | 5 | 6 | 8 | 0 | 0 | 0 | 0 |
| 5 | 5 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 6 | 6 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 7 | 7 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 8 | 8 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 9 | 9 | 4 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| 10 | 10 | 12 | 5 | 18 | 0 | 0 | 0 | 0 | 0 |
+----------+----------+-----------+-------------+----------+---------+--------------+----------------+-------------+------------+
我想要的是:
当我
insert into inventory(chara_id,item_id,item_level,item_qty)values(1,2,2,1)
这将在我的表格中插入另一个条目
否则当我插入时:
insert into inventory(chara_id,item_id,item_level,item_qty)values(1,2,0,1)
它将更新item_qty = item_qty + 1
,这是我上面清单表格中的第一行。
kudos guyz
答案 0 :(得分:1)
如果chara_id, item_id and item_level
构成UNIQUE
索引,请使用INSERT INTO ... ON DUPLICATE KEY UPDATE
这样的
INSERT INTO inventory(chara_id,item_id,item_level,item_qty)
VALUES(1,2,2,1)
ON DUPLICATE KEY UPDATE item_qty = item_qty + VALUES(item_qty);
INSERT INTO inventory(chara_id,item_id,item_level,item_qty)
VALUES(1,2,0,1)
ON DUPLICATE KEY UPDATE item_qty = item_qty + VALUES(item_qty);
这是 SQLFIddle 演示