• 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(如果子查询有一条数据被查出)

  • 相关阅读:
    C#生成图形验证码
    飞刀软件官网正式开通
    IIS7或者IIS7.5部署MVC项目时出现404错误
    office编程必不可少 [转]
    C# 利用 HttpWebRequest 和 HttpWebResponse 模拟登录有验证码的网站
    console方便用法
    24个解决实际问题的ES6代码段
    遍历对象的属性和对象的值
    前端图片处理
    Vue团队代码规范
  • 原文地址:https://www.cnblogs.com/Minghao_HU/p/2782388.html
Copyright © 2020-2023  润新知