先上数据表
student表
grade 表
SQL Union 语句
合并两个或多个select查询结果集。
select s_id from student union select s_id from grade
select s_name from student union select s_id from grade
结果集如下:
SQL group by 语句
group by 语句用于结合聚合函数,根据一个或多个列对结果集进行分组。
如查找grade表 s_id 下学科的分数和。eg:Select s_id,sum(gradeValue) as nums from grade group by s_id
练习:查询grade表下,不同的course下,对应的gradeValue都大于80的结果集,然后根据这个s_id,通过表student 得到s_name
思路:以s_id 分组查找,然后条件查找大于80的。
select s_id from grade group by s_id having min(gradeValue)>80
// 或者
select s_id from grade group by s_id having gradeValue>80
{having 自己看前面的 min()限制最小}
结果:
然后在需要根据这个s_id 查找s_name,那么只需要嵌套下就ok了。
select s_id, s_name from student where s_id in ( select grade.[s_id] from grade
group by s_id having min(grade.[gradeValue])>80)
这里用了,in关键字,还记得和=的差别,in可以查找符合这个in()里面value的都可以找到,如果用=了只能查到一个了……
结果如图: