2013-03-25 72 views
1

在這裏,我想更新item_quatity是否存在其他插入行IF NOT EXISTS INSERT,UPDATE ELSE - 不工作?

+----+--------+-----------+---------------+ 
| 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' ; 

這個查詢總是插入行,更新不工作???

+1

即是關鍵獨特之處? – CaptainCarl 2013-03-25 09:37:47

+0

你的表格模式好嗎? – hjpotter92 2013-03-25 09:38:22

回答

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

+0

改變user_item的SQL語法提示錯誤你有一個錯誤;檢查對應於你的MySQL服務器版本使用附近的正確語法手冊「user_items添加約束tb_uq(USER_ID,ITEM_ID)」在1號線
是的,我想複合柱USER_ID,ITEM_ID – 2013-03-25 09:52:05

+0

遺憾的錯字,它應該被'ALTER TABLE user_items添加約束tb_uq UNIQUE(USER_ID,ITEM_ID)' – 2013-03-25 09:55:20

+0

其工作,非常感謝你,先生 – 2013-03-25 20:23:26

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