INSERT INTO ....多行...在重复键上

时间:2013-04-11 03:37:26

标签: mysql key rows

我有一个用于网络商务网站的mysql数据库,其定价表如下所示:

priceid (int, PK, AI)
productid (int)
membershipid (int)
price (decimal(12,2))
quantity (int)

这允许项目根据membershipidquantity具有不同的定价级别(但此处的值始终为1)。

我需要使用源表来更新它:

productid (int,PK)
price1 (int)
price2 (int)
price3 (int)

我不确定如何插入数据:

COLS:[productid, price, membershipid, quantity][priceid]
ROWS:[productid, price1, 1, 1][n]
ROWS:[productid, price2, 2, 1][n]
ROWS:[productid, price3, 5, 1][n]

n =新插入时的ID,如果已存在,则为PK更新)

我知道以下代码不起作用,但基本上,我需要做的是:

INSERT INTO mysql.pricing
    (prouductid, membershipid, quantity, price) 
SELECT productid, 1, 1, price1 from mysql.source 'row n
SELECT productid, 2, 1, price2 from mysql.source 'row n+1
SELECT productid, 5, 1, price3 from mysql.source 'row n+2
ON DUPLICATE KEY UPDATE productid = VALUES(productid),membershipid = VALUES(membership), quantity = VALUES(quantity), price = VALUES(price);

我需要三个不同的行,每个行具有相同的[productid],但不同[priceid,membershipid,price]。

我找了几个答案,并且几天来我的头撞在桌子上。 有任何想法吗?任何帮助都会非常赞赏。

1 个答案:

答案 0 :(得分:0)

You have mentioned priceid (int, PK, AI)-  You can use on duplicate key update in     primary key but not on Auto Increment.  

There are two ways to solve this:  
Remove only Auto Increment from priceid and set the field as     (productid,membershipid,pricenumber) eg:  
Membershipid = 2   
productid = 33   
price1 = 11   
price2 = 12  
price3 = 13  
**priceid will be**  
33211 (price 1)  
33212 (price 2)  
33213 (price 3)  

This will always be unique...(for primary key), updating the following info.  
for memebershipid 2 , productid 33, price1 = 25, price2 = 28, price3 = 30

insert will be as follows (priceid,membershipid,productid,price,quantity)  

replace into mysql.pricing values(33211,33,2,25,1);
replace into mysql.pricing values(33222,33,2,28,1);
replace into mysql.pricing values(33233,33,2,30,1);

if the price2 has been changed from 28 to 29 you insert statment will be like this.

replace into mysql.pricing values(33222,33,2,29,1);

(using replace instead of insert for update incase of already existing primary key) 

or

other way is add another column in you mysql.pricing table with datetime, and priceid     will be primarykey  & autoincrement

mysql table columns 
priceid (int, PK, AI),productid (int),membershipid (int) price(decimal(12,2)),quantity     (int),insert_date (datetime)

Above insert can be inserted as following using now() function (which returns current     date& time)  

insert into mysql.pricing values(33,2,25,1,now());
insert into mysql.pricing values(33,2,28,1,now());
insert into mysql.pricing values(33,2,30,1,now());

updating  price2 (it will always be insert)  

insert into mysql.pricing values(33,2,29,1,now());

make all  fetch result based on max insert_date(datetime field) for respective     membershipid,price1/price2..  
Hope this solves your problem.