首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Mysql中通过关联update将一张表的一个字段更新到另外一张表中

Mysql中通过关联update将一张表的一个字段更新到另外一张表中

作者头像
翎野君
发布2023-05-12 20:15:46
发布2023-05-12 20:15:46
2.9K0
举报
文章被收录于专栏:翎野君翎野君

做什么事情

更新book_borrow表,设置其中的student_name为student表中的name,关联条件为book_borrow.student_id = student_id

student表

book_borrow表

几种不同的更新方式

保留原表数据的更新

只会更新student表中有的数据,student表中查不到的数据,在book_borrow表中还保持不变,不会更新,相当于内连接

代码语言:javascript
复制
update book_borrow br,student st set br.student_name = st.name where br.student_id = st.id;

全部以右表数据为准

更新结果以student的查询结果为准,student中没有查到的记录会全部被更新为null 相当于外连接

代码语言:javascript
复制
update book_borrow br set student_name = (select name from student where id = br.student_id);
update book_borrow br left join student st on br.student_id = st.id set br.student_name = st.name;  

将一张表的查询结果插入到另外一张表中

insert select :将一条select语句的结果插入到表中

代码语言:javascript
复制
-- insert into 表名1 (列名) select (列名) from 表名2 ;
insert into  tableA(columnA) select columnA from tableB where id=1
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-08-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 做什么事情
    • student表
    • book_borrow表
  • 几种不同的更新方式
    • 保留原表数据的更新
    • 全部以右表数据为准
  • 将一张表的查询结果插入到另外一张表中
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档