1.自行创建测试数据
2.查询学生总人数
3.查询生物课和物理课都及格的学生id和姓名
首先,查询生物课和物理课及格的同学(三表查询):
生物课及格(三表查询): select student.student_id,sname from student inner join score on student.student_id = score.student_id inner join course on course.course_id = score.course_id where cname = '生物' and score>60 物理课及格(三表查询): select student.student_id,sname from student inner join score on student.student_id = score.student_id inner join course on course.course_id = score.course_id where cname = '物理' and score>60
其次,求两个结果的并集(Mysql中与SQL Server、Oracle不同,不支持Intersect语句,因此mysql求并集需要用到INNER JOIN xxx USING xxx语句)
select distinct student.student_id,student.sname from student inner join (select student.student_id,student.sname from student inner join score on student.student_id = score.student_id inner join course on course.course_id = score.course_id where cname = '物理' and score>60) t0 using (student_id) inner join (select student.student_id,student.sname from student inner join score on student.student_id = score.student_id inner join course on course.course_id = score.course_id where cname = '生物' and score>60) t1 using (student_id);
PS:INNER JOIN xxx USING xxx语句的使用举例:
SELECT DISTINCT RESOURCE_ID FROM USER_DEFINED_VALUE INNER JOIN (SELECT DISTINCT RESOURCE_ID FROM USER_DEFINED_VALUE WHERE (COLUMN_NAME = 'A' AND VALUE in ('1')) ) t0 USING (RESOURCE_ID) INNER JOIN (SELECT DISTINCT RESOURCE_ID FROM USER_DEFINED_VALUE WHERE (COLUMN_NAME = 'B' AND VALUE in ('2')) ) t1 USING (RESOURCE_ID) 第一句话会查出表中所有的资源ID 第二句话或查出属性A='1'的资源ID,并和第一句话的查询结果取交集 第三句话或查出属性B='2'的资源ID,并和前面的查询结果取交集 using等价于join操作中的on 这样,还可以继续加其他的属性