[英]How to update table1 value with table2 value based on a table1 and table2 query?
我有兩個相似的表。 我正在組合/按摩表,因此我在一個表中擁有完整而干凈的數據。 目的是從表2中檢索Zip值並將其插入到Table1中。
Table1
Mascot City Zip
Wildcats Denver MISSING-DATA
Tigers Dallas 73843
Lions Newport 53647
Table2
Mascot City Zip
Wildcats Denver 98473
Eagles Columbus 45362
Bears Chicago 84739
我的偽代碼:
select table2 t2.Mascot, t2.City, t2.Zip
where table1 t1.Mascot, t1.City, t1.Zip = MISSING-DATA
update t1.Zip with t2.Zip
我不知道如何編寫這個復雜的查詢。 任何幫助深表感謝。
最容易理解的是使用相關子查詢 (內部查詢引用外部查詢中的值)的查詢:
update table1 set
zip = (select max(zip) from table2
where table2.mascot = table1.mascot
and table2.city = table1.city)
where zip = 'MISSING-DATA'
有更多高性能的方法,但是這樣做會足夠好,尤其是因為您的數據量很小並且是1次更新。
使用更新聯接:
UPDATE Table1 t1
INNER JOIN Table2 t2
ON t1.mascot = t2.mascot AND t1.city = t2.city
SET t1.zip = t2.zip
WHERE
t1.zip = 'MISSING'
通常,我希望這種方法能勝過使用相關子查詢的更新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.