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的区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: drop table中cascade的含
- 下一篇: ThinikPHP 前端URL模式