0

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

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

这允许项目具有基于membershipid或的不同定价级别quantity(但这里的值将始终为 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]。


几天来,我一直在寻找答案,并将头撞在桌子上。有任何想法吗?任何帮助将不胜感激。

4

1 回答 1

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. 
于 2013-04-11T05:20:09.697 回答