MySQL中exists、in及any的基本⽤法
exists子查询
【1】exists
对外表⽤loop逐条查询,每次查询都会查看exists的条件语句。
当 exists⾥的条件语句能够返回记录⾏时(⽆论记录⾏是多少,只要能返回),条件就为真 , 返回当前loop到的这条记录。反之如果exists⾥的条件语句不能返回记录⾏,条件为假,则当前loop到的这条记录被丢弃。
exists的条件就像⼀个boolean条件,当能返回结果集则为1,不能返回结果集则为 0。
语法格式如下:
select * from tables_name where [not] exists(select..);
⽰例如下:
select * from p_user_2
where EXISTS(select * from p_user where id=12)
如果p_user表中有id为12的记录,那么将返回所有p_user_2表中的记录;否则,返回记录为空。
如果是not exists,则与上述相反。
总的来说,如果A表有n条记录,那么exists查询就是将这n条记录逐条取出,然后判断n遍exists条件
【2】in
语法格式如下:
select * from A where column in (select column from B);
需要说明的是,where中,column为A的某⼀列,in 所对应的⼦查询语句返回为⼀列多⾏结果集。
注意,in所对应的select语句返回的结果⼀定是⼀列!可以为多⾏。
⽰例如下:
select * from p_user_2 where id [not] in (select id from p_user )
查询id在p_user表id集合的p_user_2的记录。not in则相反。
【3】exists与in的关系
经过sql改变,⼆者是可以达到同⼀个⽬标的:
select * from p_user_2
where id [not] in (select id from p_user );
select * from p_user_2
where [not] EXISTS (select id from p_user where id = p_user_2.id )
那么什么时候⽤exists 或者in呢?
**如果查询的两个表⼤⼩相当,那么⽤in和exists差别不⼤。 **
**如果两个表中⼀个较⼩,⼀个是⼤表,则⼦查询表⼤的⽤exists,⼦查询表⼩的⽤in: **
例如:表A(⼩表),表B(⼤表)
①⼦查询表为表B:
select * from A
where cc in (select cc from B)
//效率低,⽤到了A表上cc列的索引;
select * from A
where exists(select cc from B where )
//效率⾼,⽤到了B表上cc列的索引。
②⼦查询表为表A:
select * from B
where cc in (select cc from A)
//效率⾼,⽤到了B表上cc列的索引;
select * from B
where exists(select cc from A where )
//效率低,⽤到了A表上cc列的索引。
not in 和not exists如果查询语句使⽤了not in 那么内外表都进⾏全表扫描,没有⽤到索引;⽽not extsts 的⼦查询依然能⽤到表上的索引。
**所以⽆论哪个表⼤,⽤not exists都⽐not in要快。 **
【4】any/some/all
① any,in,some,all分别是⼦查询关键词之⼀
any 可以与=、>、>=、<、<=、<>结合起来使⽤,分别表⽰等于、⼤于、⼤于等于、⼩于、⼩于等于、不等于其中的任意⼀个数据。
all可以与=、>、>=、<、<=、<>结合是来使⽤,分别表⽰等于、⼤于、⼤于等于、⼩于、⼩于等于、不等于其中的其中的所有数据。
它们进⾏⼦查询的语法如下:
operand comparison_operator any (subquery);
operand in (subquery);
operand coparison_operator some (subquery);
operand comparison_operator all (subquery);
any,all关键字必须与⼀个⽐较操作符⼀起使⽤。
② any关键词可以理解为“对于⼦查询返回的列中的任⼀数值,如果⽐较结果为true,则返回true”。
例如:
select age from t_user where age > any (select age from t_user_copy);
假设表t_user 中有⼀⾏包含(10),t_user_copy包含(21,14,6),则表达式为true;如果t_user_copy包含(20,10),或者表
t_user_copy为空表,则表达式为false。如果表t_user_copy包含(null,null,null),则表达式为unkonwn。
all的意思是“对于⼦查询返回的列中的所有值,如果⽐较结果为true,则返回true”
例如:
select age from t_user where age > all (select age from t_user_copy);
假设表t_user 中有⼀⾏包含(10)。如果表t_user_copy包含(-5,0,+5),则表达式为true,因为10⽐t_user_copy中的查出的所有三个值⼤。如果表t_user_copy包含(12,6,null,-100),则表达式为false,因为t_user_copy中有⼀个值12⼤于10。如果表t_user_copy包含(0,null,1),则表达式为unknown。如果t_user_copy为空表,则结果为true。
③ not in /in
not in 是 “<>all”的别名,⽤法相同。
语句in 与“=any”是相同的。
例如:
select s1 from t1 where s1 = any (select s1 from t2);
select s1 from t1 where s1 in (select s1 from t2);
语句some是any的别名,⽤法相同。
例如:
select s1 from t1 where s1 <> any (select s1 from t2);
select s1 from t1 where s1 <> some (select s1 from t2);
在上述查询中some理解上就容易了“表t1中有部分s1与t2表中的s1不相等”,这种语句⽤any理解就有错了。
总结
到此这篇关于MySQL中exists、in及any基本⽤法的⽂章就介绍到这了,更多相关MySQL exists、in及any内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!