2016-07-21 8 views
0

Ich habe 2 Tabelle, Tabelle1 und Tabelle2, jeder von ihnen Zeilen hinzugefügt Tabelle1 = 2m Zeilen und Tabelle2 = 1m Zeilen und einige Zeilen aus Tabelle2 ist bereits an table1 und tabelle1 haben einzigartigen Wertsql - wie in Tabelle1 aus Tabelle2 einfügen, aber nicht den doppelten Wert einfügen

ich versuche, diesen Befehl ein:

INSERT INTO table1 (top1, top2, top3) 
    SELECT top1, top2, top3 FROM table2 

top1 ist einzigartig Wert, wie ich die Auswahl treffen kann also, wenn table2 top1 bereits auf tabelle1 top1 ist neben passieren?

+0

Was Pk, nur top1 oder top1 + top2 + top3 – Maulzey

Antwort

2

Es gibt mehrere Möglichkeiten, dies zu tun, und einige verschiedene Datenbanken bieten einfachere Methoden. Hier ist eine generische Lösung mit not exists:

INSERT INTO table1 (top1, top2, top3) 
SELECT top1, top2, top3 FROM table2 t2 
WHERE NOT EXISTS (
    select 1 
    from table1 t1 
    where t1.top1 = t2.top1) 

Eine weitere generische Option mit einem outer join \ null Kontrolle:

insert into table1 (top1, top2, top3) 
select t2.top1, t2.top2, t2.top3 
from table2 t2 
    left join table1 t1 on t2.top1 = t1.top1 
where t1.top1 is null 
+0

Dies ist, was ich suchte, danke! –

Verwandte Themen