简体   繁体   English

MySQL更新表1与表2比较

[英]Mysql update table1 compare to table2

In my mysql db i've 2 table with same field in both. 在我的mysql数据库中,我有2个表,两个表都具有相同的字段。

I need to update all the records in table2 where table1 had the same id_customer and the fields are not empty. 我需要更新table2中所有记录,其中table1具有相同的id_customer并且字段不为空。

Example: 例:

table1 表格1

id|name|surname|id_customer|email id |名称|姓| id_customer |电子邮件

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

table2 表2

id_customer|name|surname|email id_customer |名称|姓氏|电子邮件

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

The query have to update table2 adding "jon" on name 查询必须更新table2在名称上添加“ jon”

Any idea how to? 任何想法如何?

Thank you 谢谢

Try this one - 试试这个-

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);
update table2 
set table2.name = table1.name,
table2.email = table1.email,
table2.sur_name = table1.sur_name 
where table2.customer_id = table1.customer_id

I guess it might be better to join on customer_id, if it is available in both tables (as it is example). 我猜如果在两个表中都可用,则加入customer_id可能会更好(例如)。 Moreover if we need to update table1 on basic of table1, then can we update all fields, if yes above query will execute, else you can have a look at CASE clause. 此外,如果需要在table1的基础上更新table1,则可以更新所有字段,如果是,则执行上面的查询,否则可以查看CASE子句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM