mysql exist

2018-8-21 15:00:55 星期二

写了这么久SQL, 第一次去了解 exists 语句, 惭愧...

1. exists 后边的语句相当于bool判断, 如果能返回记录, 就代表true, 查不到记录就相当于false,  也就是说要么查询所有, 要么没有数据

select * from user where exists (select 1)  等价于  select * from user

2. 如果想要 exists 起到筛选的作用, 而不仅仅是bool判断的作用, 在 exists 后边的查询里要用到前边查询语句中的表的字段

select * from user where exists (select * from score where user.id = score.uid)

3. exists 会遍历前边的表, 然后每次都会查询一下后边的SQL语句判断是否有记录; 而 in 是先把后边的语句查出来放到临时表中, 然后每次遍历前边的表, 都会再遍历一遍临时表

参考: 

https://www.cnblogs.com/beijingstruggle/p/5885137.html

https://blog.csdn.net/ljxbbss/article/details/78227038

https://www.cnblogs.com/meibao/p/4973043.html (exists 和 in的效率)

原文地址:https://www.cnblogs.com/iLoveMyD/p/9511572.html