In与exist区别
查网上对in和exists的区别有很多内容和版本,现自己对in和exists作一下总结(MySQL下):
- 关于EXISTS与IN的区别:
- EXISTS检查是否有结果,判断是否有记录,返回的是一个布尔型(TRUE/FALSE)。
- IN是对结果值进行比较,判断一个字段是否存在于几个值中。
- exists做为where 条件时,是先对where 前的主查询询进行查询,然后用主查询的结果一个一个的代入exists的查询进行判断,如果为真则输出当前这一条主查询的结果,否则不输出。
- in 是把外表和内表作hash 连接,而exists是对外表作loop循环,每次loop循环再对内表进行查询
exits 相当于存在量词:表示集合存在,也就是集合不为空只作用一个集合.例如 exist P 表示P不空时为真; not exist P表示p为空时 为真 in表示一个标量和一元关系的关系。例如:s in P表示当s与P中的某个值相等时 为真; s not in P 表示s与P中的每一个值都不相等时 为真;
- select count(*) as total from tb_resources where exists (select resourcesId from tb_role_resources where roleId =1);
- /*
- *total
- *13
- */
而用in的情况则为:
- select count(*) as total from tb_resources where id in (select resourcesId from tb_role_resources where role_Id = 1);
- /*
- *total
- *9
- */
参考l
http://f.dataguru.cn/forum.php?mod=viewthread&tid=330727&page=1&extra=#pid1032091
posted on 2014-07-22 00:47 Still water run deep 阅读(890) 评论(0) 收藏 举报
浙公网安备 33010602011771号