2016-12-02 27 views
1

这里的表设计的cartitems表使用WHERE在对重复密钥更新列第

cartitems

cartitem_id PK AI 
customer_id FK 
item_id FK UNIQUE 
item_quantity INT DEFAULT 1 

我需要完成

1)如果存在item_id什么表增加item_quantity 每次用户点击“加入购物车“按钮为相同item_id

2)如果item_id尚不存在,则运行insert语句。

所以我做了这个。

CREATE DEFINER=`root`@`localhost` PROCEDURE `addItemToCart`(aCustomerId int, aProductId int) 
    BEGIN 
     INSERT INTO cart_items(customer_id,product_id) 
     VALUES(aCustomerId,aProductId) 

     ON DUPLICATE KEY UPDATE 
     item_quantity = item_quantity + 1 

     WHERE customer_id = aCustomerId AND item_id = aProductId; 
    END 

但是,当我检查了,我得到一个错误,指出,在missing semicolonitem_quantity = item_quantity + 1

我无法弄清楚是什么导致了错误。我不知道WHERE条款是否有问题。

我很感激任何帮助。

谢谢。

回答

0

ON DUPLICATE KEY UPDATE的行为得到了很好的documentation解释说:

如果你指定ON DUPLICATE KEY UPDATE,行插入,将导致在一个唯一索引或主键的重复值时,MySQL执行旧行的更新

查看您的表格,您想要增加给定客户购物车的物品数量。我在这里假设一个客户一次只能有一个购物车。所以,要在其下的MySQL执行UPDATE而不是INSERT条件是当客户项目已经出现在表格中。

为此,您可以创建通过这两个列的唯一索引:

CREATE UNIQUE INDEX unq_item_index ON cart_items (customer_id, item_id); 

然后,您可以使用以下INSERT查询:

INSERT INTO cart_items (customer_id, item_id) 
VALUES 
    (aCustomerId, anItemId) 

ON DUPLICATE KEY UPDATE 
item_quantity = item_quantity + 1 

WHERE customer_id = aCustomerId AND 
     item_id = anItemId; 

现在的行为将是如果客户/项目的新条目进入,则item_quantity将设置为默认值1,否则item_quantity将增加1

0
BEGIN 

IF NOT EXISTS(SELECT 1 FROM cart_items WHERE item_id = aProductId) 
BEGIN 
    INSERT INTO cart_items(customer_id,product_id) 
    VALUES(aCustomerId,aProductId) 
END 
ELSE 
    UPDATE cart_items SET item_quantity = item_quantity + 1 WHERE customer_id = aCustomerId AND item_id = aProductId; 
END 
0

你为什么要尝试使用WHERE条款呢?这没有意义。如果DUPLICATE KEY发生,它将更新您指定给具有相同密钥的旧记录的任何字段。所以,如果你只是删除WHERE条款它应该工作。检查this article。它指出以下两种:

INSERT INTO table (a,b,c) VALUES (1,2,3) 
    ON DUPLICATE KEY UPDATE c=c+1; 

UPDATE table SET c=c+1 WHERE a=1; 

是一样的。