Postgresql,MySQL, SQL Server的多表鏈接(join)update操做

數據庫更新時常常會join其餘表作判斷更新,PostgreSQL的寫法與其餘關係型數據庫更有不一樣,下面以SQL Server, MySQL,PostgreSQL的數據庫作對比和展現。sql

先造數據源。數據庫

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,看看不一樣的數據庫產品是怎麼作的:code

SQL Server:ci

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:it

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

需求更新:table

若是要將 a表多餘的id的city更新爲 ‘abcd’, 即 4 -> ‘abcd’, 實現update left join class

PostgreSQLdate

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
相關文章
相關標籤/搜索