關於exists和update的語法問題

發發 2014-08-27 02:19:26
有兩個表aa,bb:
lhdata@KKTEST1> select * from aa;

ID NUM
-------- --------
3 6
4 8
2 5

lhdata@KKTEST1> select * from bb;

ID
------
3
4
5

當我跑下面兩句帶exists的搜索:
lhdata@KKTEST1> select * from aa where exists (select 1 from bb where aa.id=bb.id);

ID NUM
-------- --------
3 6
4 8

lhdata@KKTEST1> select * from aa where exists (select 1 from aa,bb where aa.id=bb.id);

ID NUM
-------- --------
3 6
4 8
2 5

我的疑問是上面兩句select的差別在於哪裡?我的目的在於搜索出aa表中aa.id=bb.id的行,為什麼第二句會把不符合條件的行也搜索出來?

同樣地有另外一個關於update的問題(同樣引用上述aa,bb表):
lhdata@KKTEST1> update aa set num = (SELECT aa.id+bb.id num FROM bb WHERE bb.id = aa.id);

3 rows updated.

lhdata@KKTEST1> select * from aa;

ID NUM
-------- --------
3 6
4 8
2

我目的是要把aa表中aa.id=bb.id的行的num列update成aa.id+bb.id,為什麼出來的結果不符合條件的行的num值都update成空了呢?

望大神指點一二。
...全文
203 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
select * from aa where exists (select 1 from aa,bb where aa.id=bb.id);楼主为什么不试试select * from aa,bb where aa.id=bb.id单独执行时,结果是什么呢?实验之后就明白了
CT_LXL 2014-08-27
  • 打赏
  • 举报
回复
引用 楼主 u011360692 的回复:
有兩個表aa,bb: lhdata@KKTEST1> select * from aa; ID NUM -------- -------- 3 6 4 8 2 5 lhdata@KKTEST1> select * from bb; ID ------ 3 4 5 當我跑下面兩句帶exists的搜索: lhdata@KKTEST1> select * from aa where exists (select 1 from bb where aa.id=bb.id); ID NUM -------- -------- 3 6 4 8 lhdata@KKTEST1> select * from aa where exists (select 1 from aa,bb where aa.id=bb.id); ID NUM -------- -------- 3 6 4 8 2 5 我的疑問是上面兩句select的差別在於哪裡?我的目的在於搜索出aa表中aa.id=bb.id的行,為什麼第二句會把不符合條件的行也搜索出來? 同樣地有另外一個關於update的問題(同樣引用上述aa,bb表): lhdata@KKTEST1> update aa set num = (SELECT aa.id+bb.id num FROM bb WHERE bb.id = aa.id); 3 rows updated. lhdata@KKTEST1> select * from aa; ID NUM -------- -------- 3 6 4 8 2 我目的是要把aa表中aa.id=bb.id的行的num列update成aa.id+bb.id,為什麼出來的結果不符合條件的行的num值都update成空了呢? 望大神指點一二。
差别在于,第一个查询语句有和外查询进行连接,从而进行了条件过滤。 第二个查询内外查询没有连接,没有进行条件过滤,相当于exists条件没起作用
bw555 2014-08-27
  • 打赏
  • 举报
回复
select * from aa where exists (select 1 from aa,bb where aa.id=bb.id); 执行的效果是 如果aa和bb表只要有一条记录满足aa.id=bb.id,则查出aa表中的所有记录,否则查出0条
bw555 2014-08-27
  • 打赏
  • 举报
回复
当子查询中没有满足条件的记录时,子查询会返回空值,oracle就是这样设定的 所以这类更新最好加上where条件
update aa set num=(SELECT aa.id+bb.id num FROM bb WHERE bb.id = aa.id)
where exists (SELECT 1 FROM bb WHERE bb.id = aa.id)
bw555 2014-08-27
  • 打赏
  • 举报
回复
select * from aa where exists (select 1 from bb where aa.id=bb.id); aa.id=bb.id 是外层的aa表和子查询的bb做关联 select * from aa where exists (select 1 from aa,bb where aa.id=bb.id); aa.id=bb.id 是子查询的aa表和子查询的bb做关联 虽然都是aa.id但是一个指的是外层查询中的表,一个是子查询中的表,查询结果自然不一样了

17,134

社区成员

发帖
与我相关
我的任务
社区描述
Oracle开发相关技术讨论
社区管理员
  • 开发
  • Lucifer三思而后行
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧