mysql 子查询
子查询:一个查询语句嵌套在另一个查询语句中
*************************
子查询操作符
直接使用比较运算操作符:>、>=、=、<、<=
select * from test where num = (select num from test2)
select num from test2 返回一行记录:可正常运行
select num from test2 返回多行记录:会报错:Subquery returns more than 1 row
如果子查询语句返回多行记录,可使用如下操作符处理
any 、some:查询结果的其中一个值
all:查询结果的所有值
in:检索的值在查询返回结果中
exists:查询结果至少返回一行为true,否则为false
*************************
示例
表test1:id、num
表test2:id、num
select * from test1 where num>any(select num from test2); #true:num > 子查询其中一个num
select * from test1 where num>all(select num from test2); #true:num > 子查询num的最大值
select * from test1 where num in(select num from test2); #true:num在子查询范围中
select * from test1 where exists (select * from test2 where id>1);
select * from test1 where exists (select * from test2 where id>10);
查询结果1:
查询结果2:
查询结果3:
查询结果4:
查询结果5: