明天的明天 永远的永远 未知的一切 我与你一起承担 ??

是非成败转头空 青山依旧在 几度夕阳红 。。。
随笔 - 1274, 文章 - 0, 评论 - 214, 阅读 - 320万
  博客园  :: 首页  :: 管理
< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

数据库更新时经常会 join 其他表做判断更新,PostgreSQL 的写法与其他关系型数据库更有不同,下面以 SQL Server, MySQL,PostgreSQL 的数据库做对比和展示。

先造数据源。

复制代码
create table A(id int, city varchar(20));
create table B(id int, name varchar(20));
insert into A values(1, 'beijing');
insert into A values(2, 'shanghai');
insert into A values(3, 'guangzhou');
insert into A values(4, 'hangzhou');

insert into B values(1, 'xiaoming');
insert into B values(2, 'xiaohong');
insert into B values(3, 'xiaolv');
复制代码

 

现在我要将 xiaohong 的城市改为 shenzhen,看看不同的数据库产品是怎么做的:

SQL Server:

update A
set A.city = 'shenzhen'
from A join B
on A.id = B.id
where B.name = 'xiaohong'

 

MySQL:

update A
join B ON A.id= B. id
set A.city='shenzhen'
where B.name = 'xiaohong'

 

PostgreSQL:

update A
set city = 'shenzhen'
from B
where A.id = B.id
and B.name = 'xiaohong'

 

需求更新:

如果要将 a 表多余的 id 的 city 更新为 ‘abcd’, 即 4 -> ‘abcd’, 实现 update left join 

PostgreSQL

update a
set city = 'abcd'
from a a1
left join b 
on a1.id = b.id
where a.id = a1.id
and b.id is null

 

如果要将 a 表中的 city 用 b 表中的那么更新, 即 1- >xiaoming, 2 -> xiaohong, 3 ->xiaolv

update a
set city = b.name
from a a1
join b
on a.id = b.id
where a1.id = a.id

 

相关博文:
阅读排行:
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
历史上的今天:
2019-06-06 EF优化之启动预热
2019-06-06 AutoDetectChangesEnabled及AddRange解决EF插入的性能问题
2009-06-06 Jquery 局部刷新及 表单取值赋值 处理返回json数据 一些基本操作
2007-06-06 WinRAR 命令行备份SQLserver数据库文件 或者Vss源代码数据库目录······
2007-06-06 如何每天自动备份 SourceSafe !
点击右上角即可分享
微信分享提示