当前位置:首页 > PHP教程 > PHP总结归纳

SQLupdateselect

最常用的update语法是: update set = , set = 如果我的更新值value是从一条select语句拿出来,而且有很多列的话,用这种语法就很麻烦 第一,要select出来放在临时变量上,有很多个哦 第二,再将变量进行赋值。 列多起来非常麻烦,能不能像insert那样,把整

  最常用的update语法是:

  update

  set = , set =

  如果我的更新值value是从一条select语句拿出来,而且有很多列的话,用这种语法就很麻烦

  第一,要select出来放在临时变量上,有很多个哦

  第二,再将变量进行赋值。

  列多起来非常麻烦,能不能像insert那样,把整个select语句的结果进行插入呢?就好象下面

  insert into table1

  (c1, c2, c3)

  (select v1, v2, v3 from table2)

  答案是可以的,具体的语法如下:

  update

  set (, ) = (

  select (, )

  from

  where = )

  where ;

  下面是这样一个例子:

  两个表a、b,想使b中的memo字段值等于a表中对应id的name值

  表a:id, name

  1 王

  2 李

  3 张

  表b:id,clientname

  1

  2

  3

  (ms sql server)语句:update b set clientname = a.name from a,b where a.id = b.id

  (oralce)语句:update b set (clientname) = (select name from a where b.id = a.id)

  update set from 语句格式

  当where和set都需要关联一个表进行查询时,整个update执行时,就需要对被关联的表进行两次扫描,显然效率比较低。

  对于这种情况,sybase和sql server的解决办法是使用update...set...from...where...的语法,实际上就是从源表获取更新数据。

  在 sql 中,表连接(left join、right join、inner join 等)常常用于 select 语句,其实在 sql 语法中,这些连接也是可以用于 update 和 delete 语句的,在这些语句中使用 join 还常常得到事半功倍的效果。

  update t_orderform set t_orderform.sellerid =b.l_tuserid

  from t_orderform a left join t_productinfo b on b.l_id=a.productid

  用来同步两个表的数据!

  oralce和db2都支持的语法:

  update a set (a1, a2, a3) = (select b1, b2, b3 from b where a.id = b.id)

  ms sql server不支持这样的语法,相对应的写法为:

  update a set a1 = b1, a2 = b2, a3 = b3 from a left join b on a.id = b.id

  个人感觉ms sql server的update语法功能更为强大。ms sql server的写法:

  update a set a1 = b1, a2 = b2, a3 = b3 from a, b where a.id = b.id

  在oracle和db2中的写法就比较麻烦了,,如下:

  update a set (a1, a2, a3) = (select b1, b2, b3 from b where a.id = b.id)

  where id in (select b.id from b where a.id = b.id)

.syntaxhighlighter{padding-top:20px;padding-bottom:20px;}
【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!