sql里的update实现多表更新
sql里的update实现多表更新
在开发中,数据库来回换,而有些关键性的语法又各不相同,这是一件让开发人员很头痛的事情.本文总结了Update语句更新多表时在SQL Server,Oracle,MySQL三种数据库中的用法.我也试了SQLite数据库,都没成功,不知是不支持多表更新还是咋的. 在本例中: 我们要用表gdqlpj中的gqdltks,bztks字段数据去更新landleveldata中的同字段名的数据,条件是当landleveldata 中的GEO_Code字段值与gdqlpj中的lxqdm字段值相等时进行更新.
SQL Server语法:UPDATE { table_name WITH ( < table_hint_limited > [ ...n ] ) | view_name | rowset_function_limited } SET { column_name = { expression | DEFAULT | NULL } | @variable = expression | @variable = column = expression } [ ,...n ] { { [ FROM { < table_source > } [ ,...n ] ] [ WHERE < search_condition > ] } | [ WHERE CURRENT OF { { [ GLOBAL ] cursor_name } | cursor_variable_name } ] } [ OPTION ( < query_hint > [ ,...n ] ) ]
SQL Server示例: update a set a.gqdltks=b.gqdltks,a.bztks=b.bztks from landleveldata a,gdqlpj b where a.GEO_Code=b.lxqdm
Oracle语法: UPDATE updatedtable SET (col_name1[,col_name2...])= (SELECT col_name1,[,col_name2...] FROM srctable [WHERE where_definition])
Oracel 示例: update landleveldata a set (a.gqdltks, a.bztks)= (select b.gqdltks, b.bztks from gdqlpj b where a.GEO_Code=b.lxqdm)
MySQL语法: UPDATE table_references SET col_name1=expr1 [, col_name2=expr2 ...] [WHERE where_definition]
MySQL 示例: update landleveldata a, gdqlpj b set a.gqdltks= b.gqdltks, a.bztks= b.bztks where a.GEO_Code=b.lxqdm
有A、B张表,其记录如下:
A表
c1 c2
--------------
1 a1
2 a2
3 a3
8 a8
B表
c1 c3
--------------
1 b1
2 b1
3 b3
10 b10
A.c1与B.c1相等,用一条sql语句,实现A.c2的值更新为B.c3
------------------------
UPDATE A
SET A.c2 =B.c3
from A ,B
where A.c1=B.c1
UPDATE A
SET A.c2 =B.c3
from A inner join B on A.c1=B.c1
注意:update后面是不能跟多表的,但跟在from子句后面