关于SQL Update的四种常见写法
SQL Update常见写法
Oralce和DB2都支持的语法:
update test1
set (test1.name,test1.age)=
(select test2.name,test2.age from test2 where test2.id=test1.id)
where exists(select 1 from test2 where test2.id=test1.id)
set (test1.name,test1.age)=
(select test2.name,test2.age from test2 where test2.id=test1.id)
where exists(select 1 from test2 where test2.id=test1.id)
MS SQL Server不支持这样的语法,相对应的写法为:
update test1
set test1.name=test2.name,test1.age=test2.age
from test1
inner join test2
on test1.id=test2.id
set test1.name=test2.name,test1.age=test2.age
from test1
inner join test2
on test1.id=test2.id
update test1
set test1.name=test2.name,test1.age=test2.age
from test1,test2
where test1.id=test2.id
MySQL多表更新方法:
update test1 inner join test2
set test1.name=test2.name,test1.age=test2.age
where test1.id=test2.id
set test1.name=test2.name,test1.age=test2.age
where test1.id=test2.id
update test1,test2
set test1.name=test2.name,test1.age=test2.age
where test1.id=test2.id
通用方法(效率较低):
update test1
set name=(select name from test2 where test2.id=test1.id),
age=(select age from test2 where test2.id=test1.id)
set name=(select name from test2 where test2.id=test1.id),
age=(select age from test2 where test2.id=test1.id)
SQL中UPDATE 语句
Update 语句
Update 语句用于修改表中的数据。
语法:
UPDATE 表名称 SET 列名称 = 新值 WHERE 列名称 = 某值
Person
LastName | FirstName | Address | City |
---|---|---|---|
Gates | Bill | Xuanwumen 10 | Beijing |
Wilson | Champs-Elysees |
更新某一行中的一个列
我们为 lastname 是 "Wilson" 的人添加 firstname:
UPDATE Person SET FirstName = ‘Fred’ WHERE LastName = ‘Wilson’
结果:
LastName | FirstName | Address | City |
---|---|---|---|
Gates | Bill | Xuanwumen 10 | Beijing |
Wilson | Fred | Champs-Elysees |
更新某一行中的若干列
我们会修改地址(address),并添加城市名称(city):
UPDATE Person SET Address = ‘Zhongshan 23’, City = ‘Nanjing’
WHERE LastName = ‘Wilson’
WHERE LastName = ‘Wilson’
结果:
LastName | FirstName | Address | City |
---|---|---|---|
Gates | Bill | Xuanwumen 10 | Beijing |
Wilson | Fred | Zhongshan 23 | Nanjing |
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。