面试啦 - 提供专业面试问题及答案、面试技巧、助您成功面试!
您的当前位置:首页 > 面试题库 > IT面试题 > Database面试题 > 正文

一道SQL面试题

有三张表,学生表S,课程表C,学生课程表SC,学生可以选修多门课程,一门课程可能被多个学生选修,通过SC表关联。
(1) 写出建表以及插入语句;
(2) 写出SQL语句,查询选修了所有选修课程的学生;
(3) 写出SQL语句,查询选修了至少2门以上的课程的学生。
ANSWER:
(1) 写出建表以及插入语句;
/

create table student (
id number(10) primary key,
name varchar2(20));

create table course (
id number(10) primary key,
name varchar2(20));

create table sc(
sid number(10) references student(id),
cid number(10) references course(id),
grade number(42));

INSERT VALUES:

2) 写出SQL语句,查询选修了所有选修课程的学生;

select s.id,s.name
from student s
where s.id in(
select sid
from sc
group by sid
having count(*)=
(select count(*)
from course)
);

(3) 写出SQL语句,查询选修了至少2门以上的课程的学生。

select sid,count(*) from sc group by sid having count(*)>=2;

SELECT S.ID,S.NAME
FROM STUDENT S
WHERE S.ID IN(
select sid
from sc
group by sid
having count(*)>=2
)

drop table student cascade constraints;
drop table course cascade constraints;
drop table sc;

commit;

create table student(
id number(10) primary key,
name varchar2(15)
);

create table course(
id number(10) primary key,
name varchar2(15)
);

create table sc(
sid number(10) references student(id),
cid number(10) references course(id)
);

commit;

insert into student values(1,’star’);
insert into student values(2,’moon’);
insert into student values(3,’oracle’);
insert into student values(4,’sun’);

insert into course values(1,’Java’);
insert into course values(2,’C++’);
insert into course values(3,’Chinese’);
insert into course values(4,’English’);

insert into sc values(1,1);
insert into sc values(1,2);
insert into sc values(1,3);
insert into sc values(1,4);
insert into sc values(2,1);
insert into sc values(2,2);
insert into sc values(2,3);
insert into sc values(3,1);
insert into sc values(3,2);
insert into sc values(4,3);
insert into sc values(4,4);
commit;
;
词条:database面试题 数据库面试题
上一篇:SQL里面如何插入自动增长序列号字段 下一篇:查询优化的一般准则有哪些
与该文相关的文章

温馨提示:如果您对面试网有任何建议,请通过网站联系邮箱向我们反馈,感谢各位的建议与支持!