编写查询的sql语句的一些小技巧
Student(student_no,student_name,student_age,student_sex) 学生表
Course (course_no,course_name,teacher_no) 课程表
Sc(student_no,course_no,score)成绩表
Teacher (teacher_no,teacher_name) 教师表
案例 -:
如果在一张表中 有一列数据已经给出两个数据1,2 ,且当前数据可能出现重复,然后根据两个数据 查询对应 另一列数据时,可以将 这两个数据 作为查询条件 临时生成两张临时表 然后作查询 如下
查询 “1”课程比“2” 课程成绩高的所有学生的学号;
select a.student_no from (select student_no,score from Sc where course_no = 1) a,(select student_no ,score form Sc where course_no = 2) b where a.score>b.score and a.student_no = b.student_no ;
查询平均成绩大于60分的同学的学号和平均成绩:
Select student_no ,avg(score) as avgscore from Sc group by student_no having avg(score)>80;
查询所有同学的学号,姓名,选课数,总成绩。(多表联合查询)
select Student.student_no,Student.student_name,count(course_no) as 选课数 ,sum(score) as 总成绩 from student left join Sc on Student.student_no = Sc.student_no group by student_no;
查询性李的老师个数
select count(teacher_no) from teacher where teacher_name like ‘李%’;
查询没学过“叶平”老师的课程的所有学生的学号,姓名(两种方法)
select student_no,student_name from Student where student_no not in (select distinct(student_no) from Sc where course_no in (select course_no from Course where teacher_no = (select teacher_no from Teacher where teacher_name = '叶平')));
select student_no,student_name from Student where student_no not in (select distinct(student_no) from Sc,Teacher,Course where Sc.course_no = Course.course_no and Course.teacher_no = Teacher.teacher_no and Teacher.teacher_name = '叶平');