这里我想更新item_quatity,如果存在,则插入行
+----+--------+-----------+---------------+
| id |user_id | item_id | item_quantity |
+----+--------+-----------+----------------+
| 1 | 16 | 4 | 1 |
| 2 | 5 | 6 | 2 |
+----+--------+-----------+---------------+
INSERT INTO user_items
SET user_id = 16 ,item_id = 4 , item_quantity = 1
ON DUPLICATE KEY
UPDATE item_quantity = item_quantity + '1' ;
OR
INSERT INTO user_items
(user_id,item_id,item_quantity) VALUES ('16','4','1')
ON DUPLICATE KEY
UPDATE item_quantity= item_quantity + '1' ;
此查询始终插入行,更新不起作用???
答案 0 :(得分:4)
存在什么?用户身份? ITEM_ID?或两者user_id, item_id
?
在列user_id,item_id
上添加UNIQUE约束,它将起作用,
ALTER TABLE user_items ADD CONSTRAINT tb_uq UNIQUE (user_id, item_id)
如果您想拥有唯一的复合列user_id, item_id
答案 1 :(得分:1)
insert into user_items (id, user_id ,item_id , item_quantity) values(3,16, 4, 1)
on duplicate key update item_quantity = item_quantity + 1