有3个表,
学生表Speople:
id   name  课程表kech:
Kid  kename选课表Ck:
bid  Cid(课程id)  Sid(学生id)我想求:如果所有学生都选择了课程表里的课程,那么查看课程表的时候就不显示所有学生都选择了的课程。

解决方案 »

  1.   

    select m.* , n.* from speople m , ck n where m.id = n.sid and m.di not in 
    (select Sid from ck group by sid having count(1) = (select count(1) from kech))
    order by m.id , n.cid
      

  2.   

    --try
    select kename
    from kech
    group by kename
    having count(distinct kename)=(select count(*)from Ck)
      

  3.   

    抄袭下小麦的BLOG 实际有两种方法
    子查询
    这里不知道写什么重点,我觉得子查询分2种吧。一种是独立的子查询,和外部查询无关,它只为外部查询执行一次足矣.还有一种是相关的子查询,
    它是外部查询没执行一行它就跑一次,是动态的.
    我这里举个例子:
    --学生表
    create table #s(sno int,sname varchar(10))
    --选课表
    create table #sc(sno int,cno int,score int)
    --课程表
    create table #c(cno int,cname varchar(10))
    --插入数据
    insert #s select 
    1,'a' union all select
    2,'b' union all select 
    3,'c'
    insert #c select 
    1,'English' union all select 
    2,'Chinese' UNION ALL SELECT
    3,'Computer' 
    insert #sc select
    1,1,90 union all select
    1,2,89 union all select 
    1,3,87 union all select 
    2,2,99 union all select 
    3,1,76 union all select 
    3,3,65 
    ---查询出选修了全部课程的学生姓名---------------无关联子查询----------
    select sname
    from #s join #sc on #s.sno=#sc.sno
    group by sname
    having COUNT(cno)=(select COUNT(*) from #c)--这里就是无关联的子查询-------相关子查询------------
    select sname
    from #s s
    where not exists(select * from #c  c where not exists 
    (select *from #sc where sno=s.sno and cno=c.cno)
    )
    ------结果-----------
    /*
    sname
    ----------
    a
    */
    上面通过学生选课的经典例子说明了用不同的子查询解决问题的一个用法。
    说到EXISTS 不得不提到IN 这2个东西其实可以互相转换,但是在某些用法和效率上还是有差别的。先来说说IN和EXISTS之间的一个区别:
    IN不同于EXISTS,当输入列表包含NULL时候,它会产生一个UNKOWN。如IN (a,b,c,null)-->TRUE or UNKOWN.又因为在筛选器中UNKOWN的处理方式是false,
    使用IN和使用EXIST产生的结果是一样的,优化器产生的执行计划是一样的。
    但是 NOT EXISTS 和 IN之间的逻辑差别就大了,当然前提是输入列表中含有NULL的时候。
    create table #test1(a int)
    create table #test2(b int,c int)
    insert #test1 values(1) 
    insert #test1 values(2) 
    insert #test1 values(3) 
    insert #test2 values(1,3) 
    insert #test2 values(null,2)
    --NOT IN
    select A from #test1 where a not in(select B from #test2) 
    /*
    A
    -----------(0 行受影响)
    */
    --NOT EXISTS
    select A from #test1 where NOT EXISTS(SELECT * FROM #test2 WHERE #test1.a=b)
    /*
    A
    -----------
    2
    3
    */
    为什么在NOT IN里面没有返回2和3? 这是因为 NOT IN (A,B,NULL)返回的结果永远是 NOT TRUE 或者 NOT UNKOWN(UNKOWN),不会返回TRUE。(关于三值逻辑的判断可以参见我以前写的博客)本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/feixianxxx/archive/2009/10/20/4704774.aspx