如何根据table1和table2查询使用table2值更新table1值?

时间:2018-02-09 05:41:23

标签: mysql

我有两张相似的牌桌。我正在组合/按摩表,所以我在一个表中有完整和干净的数据。目标是从表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

我不知道如何编写这个复杂的查询。非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

最简单的理解是使用相关子查询(一个引用外部查询中的值的内部查询)的查询:

update table1 set
zip = (select max(zip) from table2
       where table2.mascot = table1.mascot
       and table2.city = table1.city)
where zip = 'MISSING-DATA'

有更多高效的方法,但这种方法表现得还不错,特别是因为您的数据量很小而且是1次更新。

答案 1 :(得分: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'

一般来说,我希望这种方法能够使用相关子查询来超越更新。

相关问题