欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

MySQL 从一张表update字段到另外一张表中

程序员文章站 2024-02-25 16:03:39
先来几个简单的示例 solution 1:  1列 update student s, city c set s.city_name = c.n...

先来几个简单的示例

solution 1:  1列

update student s, city c
  set s.city_name = c.name
 where s.city_code = c.code;

solution 2:  多个列

update a, b 

set a.title=b.title, a.name=b.name
where a.id=b.id

solution 3: 子查询

update student s set city_name = (select name from city where code = s.city_code);

我们再来看几个负责写的

例如: 把表 tk_zyt_scenery_order的 字段更新到 t_advs_order中去, 一般可能会这样写:

update t_advs_order set
 
 attribute1=(select o.order_state from tk_zyt_scenery_order o where o.order_id=`on`),
 
 attribute2=(select o.order_state from tk_zyt_scenery_order o where o.order_id=`on`)
 
 where exists (select o.order_state from tk_zyt_scenery_order o where o.order_id=`on`);

这样效率比较低下, 优化写法:

update t_advs_order a inner join tk_zyt_scenery_order s on s.order_id=a.`on` set
 
 a.attribute1=s.order_id,
 
 a.attribute2=s.order_id;