将一个sql语句的结果作为条件来判断:子查询
-- 子查询的语句,查询的列只允许一个
-- 子查询的语句,如果使用子查询和比较运算符联合使用(=,>,<,<=,>=)必须保证子查询的值不能多于一个
-- 使用 in 关键字 使可以返回多组数据 如果查询不在这里面的数据在 in 前面加上 not 即可
--子查询在where 语句的一般用法:select * from 表1 where 字段1>(子查询)
--我们的查询称为父查询,括号中嵌入的查询称为子查询
update,insert,delete一起使用,语法类似于select语句
联接-合并多个数据表中的列
子查询-将一个查询包含到另一个查询中
IN 子查询后面可跟随返回多条记录的子查询,用于检测某列的值是否在某个范围
建表
--查看表中数据
select * from stuInfo;
select * from stuMarks;
--聚合函数的使用
select count(*) from stuInfo where stuSex='男';
select stuSex,count(*) as '男女的人数'from stuInfo group by stuSex;
--表关联操作
select * from stuInfo a inner join stuMarks b on a.stuNo=b.stuNo;
--查看年龄比“李斯文”大的学员
select * from stuInfo where stuAge>(select stuAge from stuInfo where stuName='李斯文');
--查看性别和“李斯文”一致的学员
select * from stuInfo where stuSex=(select stuSex from stuInfo where stuName='李斯文');
select stuSex from stuInfo where stuName='李斯文';
--查删除别和“李斯文”一致的学员
delete from stuInfo where stuSex =(select stuSex from stuInfo where stuName='李斯文');
--查询年龄最大的学生信息
select top 1 * from stuInfo order by stuAge desc;
select * from stuInfo where stuAge=(select max(stuAge) from stuInfo );
--查询年龄最小的学生信息
select * from stuInfo where stuAge=(select min(stuAge) from stuInfo );
--查询笔试成绩成绩最高的学生
select * from stuInfo where stuNo=(select top 1 stuNo from stuMarks order by writtenExam desc);
select top 1 a.stuNo,a.stuName,b.writtenExam from stuInfo a inner join stuMarks b on a.stuNo=b.stuNo order by writtenExam desc;
--查询笔试成绩大于全班笔试平均成绩的学生记录
select * from stuInfo a inner join stuMarks b on a.stuNo=b.stuNo where writtenExam>(select avg(writtenExam) from stuMarks);
--查询笔试成绩在70分以上的学生信息(禁止联表)
select * from stuInfo where stuNo in(select stuNo from stuMarks where writtenExam>70);
--查看那些人没有考试
select * from stuInfo where stuNo not in (select stuNo from stuMarks);
select * from stuInfo a left join stuMarks b on a.stuNo=b.stuNo where writtenExam is null;