子查询的用法:
1.查询tb_stu中比你输入的那个人的名字大的年龄的学生信息
select*from tb_stu where sage>(
select sage from tb_stu where sname='名字'
)
2.比班级平均分高的学生信息
select *from tb_grade where grade>(
select avg(grade) from tb_grade
)
-- 聚合函数的使用
-- 学生表的男性的总人数
select count(*) as '男性人数' from stuInfo
where stuSex='男';
-- 男女的人数
select stuSex,count(*) from stuInfo group by stuSex;
-- 表关联操作
select * from stuInfo a inner join stuMarks b
on a.stuNo=b.stuNo;
-----------------------------------------------------
-- 将一个sql语句的结果作为条件来判断:子查询
-- 子查询的语句,查询的列只允许一个
-- 子查询的语句,如果使用=,>,<,<=,>=结果必须只有一行
-- 如果使用in,那么可以存在多行
表:
create table stuInfo --学生表
(
stuNo varchar(6) not null primary key,
stuName varchar(10) not null,
stuSex varchar(2) not null,
stuAge int not null,
stuSeat int not null identity (1, 1),
strAddress varchar(255) default ('地址不详')
);
create table stuMarks --成绩表
(
ExamNo varchar(7) not null primary key,
stuNo varchar(6) not null references stuInfo (stuNo),
writtenExam int null,
LabExam int null
);
-- 外键约束
-- 外键的值必须是主键已经有的
-- 删除主键的时候,外键对应的数据会全部删除
-- stuInfo(主表),stuMarks(从表)
insert into stuInfo(stuNo, stuName, stuSex, stuAge, strAddress)
select 's25301', '张秋丽', '男', 18, '北京海淀'
union
select 's25303', '李斯文', '女', 22, '河阳洛阳'
union
select 's25302', '李文才', '男', 85, '地址不详'
union
select 's25304', '欧阳俊雄', '男', 28, '新疆'
union
select 's25318', '梅超风', '女', 23, '地址不详';
insert into stuMarks(ExamNo, stuNo, writtenExam, LabExam)
select 's271811', 's25303', 93, 59
union
select 's271813', 's25302', 63, 91
union
select 's271816', 's25301', 90, 83
union
select 's271817', 's25318', 63, 53;
select * from stuinfo;
select * from stuMarks;