SQL server 子查询的使用


 将一个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;

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值