Mysql更新table1与table2进行比较

时间:2011-11-18 09:29:27

标签: mysql compare

在我的mysql db中我有2个表,两个表中都有相同的字段。

我需要更新table2中的所有记录,其中table1具有相同的id_customer且字段不为空。

示例:

表1

ID |名称|姓| id_customer |电子邮件

1|jon|jack|12|hello@me.com

表2

id_customer |名称|姓|电子邮件

12 | |jack|hello@me.com

查询必须更新table2,在名称

上添加“jon”

任何想法如何?

谢谢

2 个答案:

答案 0 :(得分:1)

试试这个 -

UPDATE table1 t1
  JOIN table2 t2
    ON t1.customer_id = t2.customer_id
SET
  t2.name = IF(t2.name IS NULL OR t2.name = '', t1.name, t2.name),
  t2.email = IF(t2.email IS NULL OR t2.email = '', t1.email, t2.email),
  t2.sur_name = IF(t2.sur_name IS NULL OR t2.sur_name = '', t1.sur_name, t2.sur_name);

答案 1 :(得分:0)

update table2 
set table2.name = table1.name,
table2.email = table1.email,
table2.sur_name = table1.sur_name 
where table2.customer_id = table1.customer_id

我想加入customer_id可能会更好,如果它在两个表中都可用(例如)。此外,如果我们需要在table1的基础上更新table1,那么我们可以更新所有字段,如果是,则执行查询,否则你可以查看CASE子句。