你好,游客 登录 注册 搜索
背景:
阅读新闻

Oracle中如何实现MySQL的两表关联update操作

[日期:2015-12-01] 来源:Linux社區  作者:ivictor [字体:大 中 小]

在看《MySQL 5.1参考手册》的时候,发现MySQL提供了一种两表关联update操作。

MySQL 5.1参考手册 CHM中文版 下载:http://www.linuxidc.com/Linux/2015-12/125732.htm

原文如下:

UPDATE items,month SET items.price=month.price
WHERE items.id=month.id;

在MySQL中构造表验证了一下

mysql> select * from test;
+------+--------+
| id   | salary |
+------+--------+
|    1 |    100 |
|    2 |    200 |
|    3 |    300 |
+------+--------+
3 rows in set (0.00 sec)

mysql> select * from test1;
+------+--------+
| id   | salary |
+------+--------+
|    1 |    400 |
|    2 |    500 |
+------+--------+
2 rows in set (0.00 sec)

mysql> update test,test1 set test.salary=test1.salary where test.id=test1.id;
Query OK, 2 rows affected (0.00 sec)
Rows matched: 2  Changed: 2  Warnings: 0

mysql> select * from test;
+------+--------+
| id   | salary |
+------+--------+
|    1 |    400 |
|    2 |    500 |
|    3 |    300 |
+------+--------+
3 rows in set (0.00 sec)

不难看出,上述两表关联update中只更新了test中id为1和id为2的行。

寻思了一下,Oracle中好像并没有提供两表关联的update操作,同样输入了上述语句,Oracle报错,报错信息如下:

SQL> update test,test1 set test.salary=test1.salary where test.id=test1.id;
update test,test1 set test.salary=test1.salary where test.id=test1.id
           *
第 1 行出现错误:
ORA-00971: 缺失 SET 关键字

后来,查了查官方文档,这种语法并不支持,那么Oracle中如何实现MySQL中的这种效果呢?

鼓捣了一下,虽然出来了,但还是略为复杂。

SQL> update test set test.salary=(select salary from test1 where test1.id=test.id)       
where exists (select 1 from test1 where test1.id=test.id); 已更新2行。 SQL> select * from test; ID SALARY ---------- ---------- 1 400 2 500 3 300

更多Oracle相关信息见Oracle 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=12 

本文永久更新链接地址:http://www.linuxidc.com/Linux/2015-12/125733.htm

linux
相关资讯       Oracle两表关联update  Oracle关联update 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款