如果不存在,如何插入数据,否则进行更新?

时间:2018-06-27 19:54:38

标签: mysql stored-procedures xampp

我要更新表bag中的行,否则插入新行

我在桌包中使用的这些列类型

car_name : varchar
p_id : int
quantity : int
price_one_piece : int

我将car_namep_id用作主键(复合键)

我在xampp中的MySQL例程中编写此代码,并将其保存在xampp中而没有错误,但是当我尝试在xampp中执行它时,会显示错误

  

以下查询失败:“ SET @ p0 ='mohamed'; SET @ p1 ='1'; SET @ p2 ='1'; SET @ p3 ='1'; CALL bag_insert(@ p0,@ p1,@ p2,@ p3);“   MySQL说:

#1062 - Duplicate entry 'car_name-1' for key 'PRIMARY'

代码:

IF EXISTS(SELECT * FROM bag WHERE p_id = p_id and `car_name`= car_name)THEN 
UPDATE bag set`car_name`='car_name',`p_id`=p_id,`quantity`=quantity,`price_one_piece`=price_one_piece WHERE `p_id`=p_id;

ELSE 
INSERT INTO bag (car_name,p_id,quantity,price_one_piece) VALUES (car_name,p_id,quantity,price_one_piece); 
END IF

1 个答案:

答案 0 :(得分:0)

我使用

解决了问题
> replace INSERT INTO bag (car_name,p_id,quantity,price_one_piece)
> VALUES (car_name,p_id,quantity,price_one_piece);

我在https://chartio.com/resources/tutorials/how-to-insert-if-row-does-not-exist-upsert-in-mysql/中找到了解决方法