已有表student和score

1、查询同时参加计算机和英语考试的学生的信息
思考过程:
select stu_id from score where c_name in ('计算机','英语');
select * from score where c_name in ('计算机','英语');
select * from score where c_name in ('计算机','英语') group by stu_id;
select * from score where c_name in ('计算机','英语') group by c_name;
?这个同时参加是应该怎么体现,次数?count(id)=2?
不知道同时如何体现,可以先查询满足一部分的信息
?这个学生信息是指所有的信息吗?需要把两个表的内容合在一起吗?
是指所有的信息。
拆解一下问题
参考答案:
select stu.* from student as stu
inner join score as s1
inner join score as s2
on
s1.stu_id = s2.stu_id
and stu.id = s1.stu_id
and stu.id = s2.stu_id
where s1.c_name = '计算机'
and s2.c_name = '英语' ;

注意:可以连着两个连接。
2、查询计算机考试成绩按从高到低进行排序
select * from score where c_name='计算机' order by grade desc;

3、查询姓张或者姓王的同学的姓名、院系和考试科目及成绩
思考过程:
(1)select * from score as sc left join student as s on s.id=sc.stu_id where s.name like '张%' or s.name like '王%';
(2)select t.name,t.department,t.c_name,t.grade from
(select * from score as sc left join student as s on s.id=sc.stu_id where s.name like '张%' or s.name like '王%' ) as t ;

注意:两个模糊逻辑匹配的写法 where 字段1 like A or 字段2 like B
4、查询都是湖南的学生的姓名、年龄、院系和科目及成绩
思考过程:
(1)select * from student where address like '湖南%';
(2)select t.name,t.department,t.c_name,t.grade, t.address from
(select * from score as sc left join student as s on s.id=sc.stu_id where address like '湖南%' ) as t ;
(3)select t.name,t.department,t.c_name,t.grade,date_format(now(),'%Y')-t.birth as age,t.address from
(select * from score as sc left join student as s on s.id=sc.stu_id where address like '湖南%' ) as t ;

注意:一直birth年份,如何计算年龄,这一部分还需要后续深化学习。
这里的年龄可以直接写成: 2020-birth as age。
错误记录
1、ERROR 1248 (42000): Every derived table must have its own alias

2、ERROR 1060 (42S21): Duplicate column name 'id'
问题背景:
通过左连接创建了一个表,但是存在重复的字段名称,应该怎么办?
可以先修改连接前的表的字段名称,然后再进行连接。

发现一个问题,字段名称为‘index’会出现错误,所以建议最好不要改字段名为index,举例如下:

总结:
拿到一个题目,首先需要分清逻辑,理清查询先后;其次,在遇到问题时可以多换角度解决问题,不要死磕。
网友评论