首先需要的建立表数据如下:
- create table if not exists student
- (
- SNO varchar(20) primary key,
- SNAME varchar(20) character set gbk,
- AGE int,
- SEX char(2) character set gbk CHECK(SEX IN('男','女'))
- );
- insert into student values('1','李强',23,'男');
- insert into student values('2','刘丽',22,'女');
- insert into student values('5','张友',22,'男');
- create table if not exists course
- (
- CNO varchar(20) primary key,
- CNAME varchar(20) character set gbk,
- TEACHER varchar(20) character set gbk
- );
- insert into course values('K1','C语言','王华');
- insert into course values('K5','数据库原理','程军');
- insert into course values('K8','编译原理','程军');
- create table if not exists sc
- (
- SNO varchar(20) NOT NULL,
- CNO varchar(20) NOT NULL,
- SCORE int NOT NULL,
- primary key (SNO,CNO),
- foreign key (SNO) references student(SNO),
- foreign key (CNO) references course(CNO)
- );
- insert into sc values('1','K1',83);
- insert into sc values('2','K1',85);
- insert into sc values('5','K1',92);
- insert into sc values('2','K5',90);
- insert into sc values('5','K5',84);
- insert into sc values('5','K8',80);
方案一:
select * from (select s.sname,count(*) num from
student s,sc sc1,course c where s.sno=sc1.sno and c.cno=sc1.cno group by s.sno) res where res.num>=3;
方案一得思路就是把所有学生的信息全部通过内连接查询出来,并且分组,把该结果当做是一个res表,之后再从表里通过num查询出num>=3的学生
方案二:
select * from student s,sc sc1,course c where s.sno=sc1.sno and c.cno=sc1.cno and group by s.sno having count(*)>=3
方案二的思路和上面差不多,但是更为简洁,直接having语句直接分组,由代码可以看得出,having count(*)>=3相当于方案一的把结果集封装为表,再通过表的字段判断