mysql联表更新
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只是语法示例,没有什么具体的业务含义。
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
阅读量:152
阅读量:135
阅读量:23
阅读量:168
阅读量:115