MySQL数据库学习记录:基本操作

作业练习

创建表

–(1)学生表

Student(s_id,s_name,s_age) --学生编号,学生姓名,学生年龄

–(2) 课程表

Course(c_id,c_name) – --课程编号, 课程名称

–(3) 成绩表

Score(s_id,c_id,s_score) --学生编号,课程编号,分数

语句如下:

 

添加信息

-------------(使用insert批量插入语句时,不同行用逗号隔开)-------------

向student表中批量插入信息

 

 

 insert into student(s_id,s_name,s_age)values(1,'小吴',13),(2,'小明',14),(3,'小强',23),(4,'小齐',18),(5,'小刘',17),(6,'小李',20);

向course表中批量插入信息

 insert into course(c_id,c_name)
 values
 (001,'语文'),(002,'数学'),(003,'英语'),(004,'化学'),(005,'物理'),(006,'物理');

向score表中批量插入信息

 insert into score(s_id,c_id,s_score)
 values
 (1,2,90),(2,2,67),(3,3,88),(4,5,57),(5,4,90),(6,6,80);

 显示表内容:

如需显示表内容,用select *from 表名 where 条件;自己查找即可

接下来的查询皆是由此衍生出来的

 

 

 练习mysql语句:

1.查询年龄在15岁至21岁的同学信息

 select *from student where s_age>15 and s_age<21;

2.查询成绩大于60的同学的名字和学号

select stu.s_id,stu.s_name from student stu,score sc
where stu.s_id=sc.s_id
and sc.s_score>60;

3.查询选了“数学”的课程的所有同学的平均成绩

select AVG(sc.s_score) from student stu,score sc,course co '所有同学数学平均分'
 where stu.s_id=sc.s_id
 and co.c_name='数学';

 

 方法2:使用IN谓词的子查询

上面三个示例还可以用IN谓词来查询,首先解释下何为谓词,通常我们用的>、<、and、or、is null、is not null、in、not in等逻辑词返回的结果都是true,false和不确定。

这一类返回逻辑值的词汇就叫做查询的谓词,而IN谓词也是其中一种,表示是否包含其中。

比如下面语句:

select*from score where s_score in (88,90);

该语句的意思是,判断列属性s_score 中列值为88和90的所有行值。

 

 修改为not in查询

select*from score where s_score not in (88,90);

则返回下列内容:即不是88,90的行内容。

 

好了,到这里对IN子查询的铺垫已完成

我们进入正题,讨论下嵌套select的IN子查询。

先看下执行语句;

1.查询年龄在15岁至21岁的同学信息:
select s_id,s_name  
    from student  
    where 15<s_age<20;
2.查询成绩大于60的同学的名字和学号:
select s_id,s_name 
    from student  
    where s_id IN 
    (select s_id from score where s_score>60);
3.查询选了“数学”的课程的所有同学的平均成绩:
select AVG(s_score) 
    from score  
    where c_id IN 
    (select c_id from course where c_name='数学');

即在IN后面又进行了一次查询,我们把后面的语句返回的结果作为一个类似于上述(80,90)的列表就好理解了。

返回结果见  ↑连表查询。

 

posted @ 2020-03-30 17:34  Vinci-Q  阅读(285)  评论(0)    收藏  举报