2016-04-21 4 views
0

Ich habe eine bestehende MySQL-Tabelle mit Daten geladen (TblParts)Mysql Abfrage-Update Mit Bedingungen

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 

Ich habe eine zweite Tabelle mit neuen Informationen (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 

ich brauche TblParts zu aktualisieren mit TblPartsNeue Daten

wenn Code vorhanden ist, und Standort = global dann Bestand und Preis aktualisieren, wenn Code vorhanden ist, aber Standort <> Global dann Datensatz mit gleichem Code einfügen an d Distinct Ort, wenn Code nicht dann Exist hinzufügen es

Die Ausgabe von TblParts Must Be:

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

Was haben Sie versucht? – Strawberry

+0

Was ist deine Frage? Hast du es schon probiert? – Dominik

+0

Weil MySql keinen MERGE-Befehl hat, müssen Sie eine INSERT- und eine UPDATE-Abfrage schreiben. –

Antwort

0

Schritt 1: ein Primärschlüssel für Spalten (Code, Ort) erstellen mit Hilfe der folgenden Abfrage

alter table TblParts add constraint pk_1 PRIMARY KEY(Code,Location); 

Schritt 2: nun die Tabelle mit TableNewParts aktualisiert Tabellen der Daten unter Abfrage mit

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, ich kann diese Abfrage verwenden, weil die ID von tableNewParts nicht die gleiche der TblParts ist. Ich brauche Vergleiche mit Code und Standort. – Peter013

0

Try this:

/* 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)) 

Sie nicht wissen, was die ID-Spalte steht. Wenn es sich um einen autoinkrementierten Schlüssel handelt, fügen Sie einfach 0 zur Feldliste unter der INSERT-Anweisung hinzu:

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)) 
Verwandte Themen