mysql联表更新

 时间:2026-02-12 06:04:16

1、假定有两张表,一张用户表user,另一张用户评论表userComment。

两张表联合查询,更新其中一张表,sql写法如下:

update user a, userComment b

set b.userName= a.userName, b.userPic=a.userPic

where a.userId=b.userId

and a.userStatus=0

上面的sql将user表中userName和userPic字段属性同步到userComment表中,条件是userId相同。

表a和表b不是原始的基本表,如果是查询的结果集也能执行。

2、两张表联合查询,更新其中一张表,也能用inner join 连接。

update user a

inner join userComment b on a.userId=b.userId

set b.userName= a.userName, b.userPic=a.userPic

where a.userStatus=0

注意也可以用外连接left join查询更新。

3、上面的写法都是两张表关联,更新其中一张,其实也能两张都更新,写法基本相同。

update user a, userComment b

set b.userName= a.userName, b.userPic=a.userPic,b.commentCount=a.commentCount

where a.userId=b.userId

and a.userStatus=0

当然上面的sql只是语法示例,没有什么具体的业务含义。

  • ff14刷马副本怎么开
  • 黎明前线rpg攻略
  • 破晓传说sp怎么刷
  • 艾尔登法环职业技能怎么学
  • 《永恒之柱2:死亡之火》旧城神庙
  • 热门搜索
    教师节英语手抄报 环保手抄报文字 安全文明手抄报 新学期新打算手抄报 英语手抄报资料 父亲节手抄报好画字少 感恩母亲的手抄报图片 我爱读书手抄报图片 2020国庆节手抄报内容 欢庆国庆手抄报