一、SQL语法——12-子查询

子查询

1.子查询就是指在查询语句中嵌套另一个查询,子查询可以支持多层嵌套。对于一个普通的嵌套查询而言,子查询可以出现在两个位置:

(1)出现在from之后当成数据表,这种做法也被称为是行内视图,因为该子查询的实质就是一个临时视图;

(2)出现在where条件之后作为过滤条件的值。

2.使用子查询时应该注意以下几点:

(1)子查询要用括号括起来;

(2)把子查询当做是数据表时(出现在from之后),可以为该子查询起别名,尤其是作为前缀限制数据列时,必须给子查询起别名;

(3)把子查询当做过滤条件时,把查询放在比较运算符的右边以增强查询的可读性;

(4)把子查询当做是过滤条件时,单行子查询使用单行运算符,多行子查询使用多行运算符。

3.示例:

 

--建立所使用的表,并添加数据
create table teacher_table(
    teacher_id int auto_increment,
    teacher_name varchar(255),
    primary key(teacher_id)
);
create table student_table(
    student_id int auto_increment primary key,
    student_name varchar(255),
    java_teacher int,
    foreign key (java_teacher) references teacher_table(teacher_id)
);

--为表中添加数据
insert into teacher_table
values
(null,'teacher_1'),
(null,'teacher_2'),
(null,'teacher_3');

insert into student_table
values
(null,'studnet_1',1),
(null,'studnet_2',1),
(null,'studnet_3',1),
(null,'studnet_4',2),
(null,'studnet_5',2),
(null,null,2),
(null,'studnet_6',null);


--把子查询当做是数据表
select * 
--放在from之后当成数据表
from (select * from student_table) t
where t.java_teacher>1;

--把子查询当做是where条件中的值,如果子查询返回单行、单列值,则被当成一个标量使用
select *
from student_table
where 
java_teacher > (select teacher_id from teacher_table where name = 'name2');


--如果子查询返回多个值,则需要使用in、ant、all等关键字
select *
from student_table
where student_id
--使用在in之后使用子查询,子查询的返回值当成多个值构成的一个列表
in
(select teacher_id from teacher_table);

 

 

 

posted @ 2017-08-03 16:00  丶theDawn  阅读(647)  评论(0编辑  收藏  举报