欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

sql中exists替换in的区别

发布时间:2024/4/17 编程问答 44 豆豆
生活随笔 收集整理的这篇文章主要介绍了 sql中exists替换in的区别 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

在sql中使用exists替换in查询时要注意使用exists时一定要关联主查询和子查询的关联不然查询会得不到相应的结果如下语句:
 语句一使用in查询:
 select realname from Users where Users.UserId  in
 (select Gallery.Galleries.CreatorId from  Gallery.Galleries  group by Gallery.Galleries.CreatorId
 having COUNT(Gallery.Galleries.CreatorId)>1 ) Order by UserId 
 语句二使用exists查询:
 select realname from Users where exists
 (select Gallery.Galleries.CreatorId from  Gallery.Galleries  group by Gallery.Galleries.CreatorId
 having COUNT(Gallery.Galleries.CreatorId)>1 ) Order by UserId
 乍一看没有错误,但是语句二忘记了主查询和子查询的主键的关联,导致把主查询的所有内容查出来。
 语句二的正确写法应该是:
  select * from Gallery.Galleries as A where exists (select A .CreatorId from  Gallery.Galleries as B
  Where A.CreatorId = B.CreatorId  group by B.CreatorId having COUNT(B.CreatorId)>1)Order by CreatorId
注:exists是boolean运算的只要字查询的结果集有一条数据结果就为真where后的条件就为真所以第二条查询语句等价于
 select realname from Users where 1=1 Order by UserId(如果子查询有一条数据被查出)

转载于:https://www.cnblogs.com/Minghao_HU/archive/2012/11/22/2782388.html

总结

以上是生活随笔为你收集整理的sql中exists替换in的区别的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。