sql语言 含有包含关系的查询 (含mysql 和sql sever)

一、sql中查询包含关系的查询

       sql语句中包含关系可以使用 in 和exist,但有些时候仅仅用这两个是不够的,还有表示方法是  not exist(b expect a )可以表示a包含b。

二、这里举一个例子

      查询中涉及2个表,一个student表,一个sc表(用来储存每个学生的id和对应的选课id还有该学生该课的成绩)

    具体表的内容如下(不全):

student表:                                                                             sc表:

       

  问题:查询至少选修了学号为“31401”的学生所选修的所有课程的学生的学号和姓名。

emmmm...

如果套用之前的公式:

 1 select sno,sname
 2 from student as s1
 3 where not exists(
 4             (select cno
 5              from sc
 6              where sno='31401')
 7              except
 8             (select sc.cno
 9              from sc,student as s2
10              where sc.sno=s2.sno and s1.sname=s2.sname));

  然而遗憾的是,mysql不能使用except语句,那么我们使用另一种解决方法

 1 -- 找出学号为31401的同学所选课程的集合a
 2 CREATE OR REPLACE VIEW a as
 3 select sc.cno
 4 from sc
 5 where sno=31401;
 6 
 7 -- 找出其他同学选修了集合a里的学生id和课程id的集合
 8 CREATE OR REPLACE VIEW b as
 9 select a.cno,sno
10 from a left join sc on a.cno=sc.cno;
11 
12 -- 得出结果
13 select sno, sname
14 from student
15 where sno in(select sno 
16              from b group by sno having count(distinct cno)=3);

 

猜你喜欢

转载自www.cnblogs.com/youyou0/p/8988474.html