`
reallyafei
  • 浏览: 97442 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

sql语句优化

阅读更多

有如下三个表
1.查询出没有选择大学物理课程的所有学生
2.查询出超过3个人选择的所有课程

student 表

 

SNO NAME
1 张三
2 李四
3 王五
4 黄七
5 刘八


course 表

 

CNO NAME
001 大学物理
002 大学英语
003 C语言
004 高等数学


course_select 表

 

SNO CNO
1 001
1 002
1 003
2 001
2 003
3 002
3 003
4 001
4 004
5 001
5 002



我写的sql语句如下
1. select s.sno, max(s.name) from course_select t, course c, student s
    where t.cno=c.cno and t.sno=s.sno group by s.sno
    having count(case when c.name ='大学物理' then s.sno end) = 0

 

    --或者

    select s.sno,s.name from student s where s.sno not in (
    select distinct cs.sno from course c,course_select cs 
    where c.cno=cs.cno and c.name='大学物理')

 
2. select t.cno, t.name from (
    select c.cno, c.name,count(c.cno) n from course c, course_select cs
    where c.cno = cs.cno group by c.cno, c.name) t where n>3

 

    --或者(抛兄给出的,我想应该是最优化的了。)

    select t.cno, max(c.name) from course c, course_select t
    where c.cno = t.cno group by t.cno having count(t.cno) > 3


各位大虾看看,我写得对不对啊,还有没有更好的写法啊,还请不吝赐教!

 

分享到:
评论
4 楼 抛出异常的爱 2009-05-27  
是不等啊....没看清题
用case 语句 行变列....
3 楼 reallyafei 2009-05-27  
抛出异常的爱 写道
select a.name
from a , b ,c
where 1=1
and a.sno = c.sno
and b.cno = c. cno
and b.name = #name#

这个不符合啊,我要查出的是不包含的啊
抛出异常的爱 写道
select max(b.name)
from b, c
where 1=1
and b.cno = c.cno
group by c.cno
haveing count(c.sno)>3

恩,这个不错,我已经加上去了,谢谢抛兄指点!
2 楼 抛出异常的爱 2009-05-27  
select a.name
from a , b ,c
where 1=1
and a.sno = c.sno
and b.cno = c. cno
and b.name = #name#

select max(b.name)
from b, c
where 1=1
and b.cno = c.cno
group by c.cno
haveing count(c.sno)>3
1 楼 reallyafei 2009-05-26  
晕,怎么没有更好的写法吗

相关推荐

Global site tag (gtag.js) - Google Analytics