sql语句的子查询
子查询又叫嵌套查询,总结一下子查询的各种操作和处理,以便于记忆和熟练的运用。
概念:什么是子查询?
子查询就是将一个查询语句嵌套在另一个查询语句中,内层语句的查询结果,可以作为外层查询语句的条件,本文重点讲解的是放在where或者having关键词之后的情况,当然不仅限这种情形。
子查询分为一下三种情况(这里只总结运用较多的三种)
一、列子查询(多行子查询,即子查询的结果集是多行单列),位置放在where和having之后。
包含一下几种常见的情形:
1、使用【not】in 的子查询
2、使用比较运算符的子查询(=、> 、 >=、 <=、 <>、 !=、 <=>)
3、使用[not] exists 的子查询
4、使用any some 或者 all 的子查询,具体如右图:
操作浮 | 含义 |
IN/NOT IN | 等于列表中的任意一个 |
ANY|SOME | 和子查询返回的某一个值比较 |
ALL | 和子查询返回的所有值比较 |
运算符 |关键字 | any | some | all |
> >= | 最小值 | 最小值 | 最大值 |
< <= | 最大值 | 最大值 | 最小值 |
= | 任意值 | 任意值 | |
<> != | 任意值 |
(仅示例)
select id ,username from student where score >=any(select level from scholarship);大于等于任意一个,即取最小值
select id ,username from student where score >=some(select level from scholarship)同上
select id ,username from student where score >=all(select level from scholarship)大于等于所有的,就是大于等于里面最大的那个
其他情况参考这个示例
二、标量子查询
标量子查询的子结果集是单行单列,并且子查询条件一般放在where或者having的后面,要注意放在()内,且不加“;”。
举例说明一下:
select * from employees
where salary >(
select salary from employees where
last_name='Abel'
);
select department_id ,min(salary) from employees
group by department_id
having min(salary) >(
select min(salay)
from employees where department_id =50
);
三、行子查询(结果集是一行多列或者多行多列,用法较少,不做推荐)
举例说明:
select * from employees
where (employee_id ,salary )=(
select min(employee_id),max(salary)
from employees
);
当然用之前的方法也是可以解决的:
select * from empioyees
where employee_id=(
select min(employee_id) from employees
)
and
salary=(
select max(salary) from employees
);
当然子查询还有一些其他的用法,比如下面的在创建表格时的运用。
将查询结果写入到数据表格中
insert table [column_name,…….] select column_name,……. from table;
创建数据表的同时将查询结果写入到数据表中
create table if not exists table_name [create_definition,……] select_statement
ps:这里需要注意的是,新建表格的字段要与查询的字段保持一致,才可以按照对应的字段生成数据,如果不一致,会在原来的基础上生成新的字段。
create table test2 (id tinyint unsigned auto_increment key ,num tinyint unsigned ) select id ,level from scholarship ;
+------+----+-------+
| num | id | level |
+------+----+-------+
| NULL | 1 | 90 |
| NULL | 2 | 80 |
| NULL | 3 | 70 |
+------+----+-------+
这样就多出了一个level字段或者说num字段没有用上,如果我们把num字段改成level就能生成合适的表格内容了。
+----+-------+
| id | level |
+----+-------+
| 1 | 90 |
| 2 | 80 |
| 3 | 70 |
+----+-------+
另外还有一些子查询语句是放在select下面的,举一个例子说明一下:
select d.*,(
select count(*)
from employees e
where e.department=d.department
)
from departments d;
select (
select department_name from departments d
join employees e
on d.department_id =e.department_id
) from departments d;
还有一部分是放在from后面的,一般from后面跟着的是表格,这里相当于把子查询的结果集当成是表格来处理,不再做示例了,有兴趣的可以百度一下。
还没有评论,来说两句吧...