2016-04-21 71 views
0

我有一個現有的MySQL表數據加載(TblParts)MySQL查詢更新的條件

Code Stock Price Location id 
1  10 1000 Global 1 
2  5 1500 Office 2 
3  2 500 Global 3 
4  1 100 Global 4 

我有新的信息,第二個表(TblNewParts)

Code Stock Price Location id 
1 30 2000 Global 1 
2 5  1000 Global 2 
3 10 5000 Global 3 
4 30 200  Global 4 
5 40 500  Global 5 

我需要更新TblParts與TblPart新數據

如果代碼存在,並且位置=全局,則更新股票和價格(如果代碼存在但位置<>全局然後插入具有相同代碼的記錄如果d鮮明位置代碼不存在,則添加它

TblParts的輸出必須:

Code Stock Price Location 
1 30 2000 Global 
2 5  1500 Office 
3 10 5000 Global 
4 30 200 Global 
5 40 500 Global 
+1

你試過了什麼? – Strawberry

+0

你的問題是什麼?你已經試過了嗎? – Dominik

+0

因爲MySql沒有MERGE命令,你必須編寫一個INSERT和一個UPDATE查詢 –

回答

0

步驟1:創建一個主鍵使用以下查詢

列(代碼,位置)
alter table TblParts add constraint pk_1 PRIMARY KEY(Code,Location); 

步驟2:現在使用下面的查詢TableNewParts表的數據更新該表

insert into TblParts(Code,Stock,Price,Location) select (Code,Stock,Price,Location) from TblNewParts on duplicate key update Stock=values(Stock),Price=values(Price); 
+0

Thnks,I可以使用該查詢,因爲tableNewParts的ID與TblParts不相同。我需要與代碼和位置進行比較。 – Peter013

0

試試這個:

/* if Code Exist, And Location = Global then Update Stock and Price */ 
UPDATE 
    tblparts p INNER JOIN tblnewparts np 
    ON np.code = p.code AND p.location = 'Global' 
SET p.price = np.price, p.stock = np.stock; 

/* if Code Exist, But Location <> Global then Insert Record with Same Code */ 
/* and Distinct Location */ 
/* if code Not Exist then Add it */ 
INSERT INTO tblparts (code, stock, price, location) 
    SELECT code, stock, price, location 
    FROM tblnewparts np 
    WHERE NOT EXISTS (SELECT * FROM tblparts 
        WHERE (code = np.code AND location = np.location) 
          OR 
         (code= np.code)) 

不知道是什麼ID列代表。如果它是一個自動增量密鑰,只需在INSERT語句下的字段列表中加0:

INSERT INTO tblparts (code, stock, price, location, id) 
    SELECT code, stock, price, location, 0 
    FROM tblnewparts np 
    WHERE NOT EXISTS (SELECT * FROM tblparts 
        WHERE (code = np.code AND location = np.location) 
          OR 
         (code= np.code))