2013-07-18 118 views
1

我有一個pricing表和一個products表在MySQL 5.1.70內置。如何更新同一個表中另一條記錄的記錄?

新的價格表結構:

`priceid` int(11) NOT NULL AUTO_INCREMENT 
`itemid` int(11) NOT NULL DEFAULT '0' 
`class` enum('standard','wholesale') NOT NULL 
`price` decimal(12,2) NOT NULL DEFAULT '0.00' 
`owner` int(11) NOT NULL DEFAULT '0' 

舊的價格表結構:

`priceid` int(11) NOT NULL AUTO_INCREMENT 
`itemid` int(11) NOT NULL DEFAULT '0' 
`price` decimal(12,2) NOT NULL DEFAULT '0.00' 
`owner` int(11) NOT NULL DEFAULT '0' 

新產品的表結構:

`itemid` int(11) NOT NULL AUTO_INCREMENT 
`title` varchar(255) NOT NULL DEFAULT '' 
`msrp` decimal(12,2) NOT NULL DEFAULT '0.00' 

舊產品表結構:

`itemid` int(11) NOT NULL AUTO_INCREMENT 
`title` varchar(255) NOT NULL DEFAULT '' 
`wholesale_price` decimal(12,2) NOT NULL DEFAULT '0.00' 
`msrp` decimal(12,2) NOT NULL DEFAULT '0.00' 

下面是來自新產品的表的例子行:

'12345', 'Toy Drum', '25.00' 

以下是新的定價表中的兩個例子行同樣項目:

'123', '12345', 'wholesale', '10.00', '2' 
'124', '12345', 'standard', '20.00', '2' 

我有以下查詢我「M試圖返工,使與上述新表設置工作,因爲舊體制在products表有wholesale_price

UPDATE products, pricing, price_rules 
SET pricing.price = IF(
    price_rules.markdown > 0, 
    products.msrp - price_rules.markdown * products.msrp, 
    products.wholesale_price + price_rules.markup * products.wholesale_price 
) WHERE 
    products.itemid = pricing.itemid AND 
    pricing.owner = price_rules.owner; 

複雜性在於批發價格和標準價格現在在相同的itemid之下,但是不同的class在同一張表中。

如何使這個查詢在新的表結構下工作(高效)?

表格有大約200,000條記錄。

+0

我不明白是什麼問題。爲什麼你的查詢不起作用?看在上帝的份上,下一次你問一個問題只是發佈表結構而不是這個「這張表有這個,那個表有這個」文本。 – fancyPants

+0

@fancyPants我編輯的帖子更具可讀性。查詢將不起作用,因爲批發價格已移至與標準價格相同的表格。 – eComEvo

+0

這是什麼'price_rules.markdown'?它在你的新表中缺失。 – fancyPants

回答

0

首先,你需要一個真正有效的查詢 - 你以後會擔心效率問題。

看看this SQLFiddle demo,這個例子展示瞭如何將「批發」和「標準」值從同一個表中的兩行進行配對。

這裏是another demo,舉例說明更新查詢的樣子(查詢位於構建模式選項卡的底部),下面顯示的是在示例數據上運行此更新後的結果。

UPDATE products, pricing new, pricing old, price_rules 
SET new.price = IF(
    price_rules.markdown > 0, 
    products.msrp - price_rules.markdown * products.msrp, 
    products.wholesale_price + price_rules.markup * products.wholesale_price 
) WHERE 
    old.class = 'wholesale' AND 
    new.class = 'standard' AND 
    old.itemid = new.itemid AND 
    products.itemid = new.itemid AND 
    new.owner = price_rules.owner; 
+0

工作很好!謝謝! :) – eComEvo

相關問題