Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 views
in Technique[技术] by (71.8m points)

mysql - How to update child table when a duplicate is detected on the parent table using ON DUPLICATE KEY UPDATE

I have a Products table which is the parent table of Price, so I am inserting data to both tables simultaneously using a stored procedure, when I am inserting a duplicate record I want to update the old record using the new record on both tables, but on my case it only updates the Products table, and I get Error Code: 1062. Duplicate entry '13-1' for key 'Price.PRIMARY' when updating the Price table. I need assistance on how to overcome this issue.

Here is my stored procedure

BEGIN
declare ProductId int;

select ProductID INTO ProductId from Products
where
Products.ProductName = p_Name and Products.ProductURL = p_Url;

if(ProductId is null ) then
BEGIN
 Insert into Products(ProductName,ProductDescription,ProductURL,ImageURL,Barcode, CategoryID)
 values(p_Name,p_Descr,p_Url,image_url,p_BarCode,p_cat)

 ON DUPLICATE KEY UPDATE
  ProductName = p_Name, ProductDescription=p_Descr, ProductURL=p_Url, ImageURL = image_url, Barcode = 
p_BarCode, CategoryID = p_cat;
 SET ProductId = LAST_INSERT_ID();
END;

END IF;

insert into Price(ProductID,StoreID,SpecialPrice,RegularPrice,FinalPrice,DateUpdated)
values(ProductId,storeid,s_price,r_price,f_price,dateUpated);

END

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...