如果特定列存在字段,如何更新

How to update if field exist for a specific column

我的请求有问题,我必须更新我现有的字段而不是进行插入,因为它将被复制并且我已经知道 ON DUPLICATE KEY UPDATE 或 REPLACE 但它不起作用目标会是更新我的产品数量而不是插入一些。我尝试通过触发器,但它也不起作用,你有解决我的问题的方法吗?

INSERT INTO cart(product_id, quantity) VALUES (4, quantity +1 )

但是如果该产品已经存在,它会向我添加一行,我希望它能够自动检测并更新它,因为我知道我的字段不是键

UPDATE cart SET quantity = quantity+1 WHERE id= id

这是我的触发器:

BEGIN
IF EXISTS (SELECT product_id FROM cart WHERE product_id = NEW.product_id)
THEN
    UPDATE cart SET quantity = NEW.quantity WHERE id = NEW.user_id;
ELSE
    INSERT INTO cart(product_id, quantity) VALUES (NEW.product_id, NEW.quantity);        
END IF;  

结束

这是一个问题: 两行相同,对于这个例子,我希望一行像 id 1

Image expalin problem

非常感谢,对不起我的英语和表达

无需触发器。您可以使用 MySQL insert ... on duplicate key syntax.

insert into cart(product_id, quantity) 
    values (4, 1)
    on duplicate key update quantity = quantity + values(quantity)

为此,您需要在列 product_id 上设置唯一约束(或主键约束)。

使用此语法,如果已存在与您尝试插入的记录具有相同 product_id 的记录,则会执行 update,添加新的 quantity 到现有记录。