mysql基础(三)

0x03 数据更新

1、插入数据
①将一个新学生插入元组

insert into student(sno,sname,ssex,sdept,sage)values('201215128','张三','男','is',18);

或者

insert into student values('201215126','李四','男','is',20);

2、修改数据
三种修改方式:

  • 修改某一个元组的值
  • 修改多个元组的值
  • 带子查询的修改语句
    ①将学生201215126的年龄改为22
update student set sage=22 where sno='201215126';


②将所有学生的年龄增加1岁

update student set sage=sage+1;


③将计算机科学系全体学生的成绩置零

update sc set grade=0 where sno in (select sno from student where sdept='cs');

3、删除数据
三种删除方式:

  • 删除某一个元组的值
  • 删除多个元组的值
  • 带子查询的删除语句

①删除学号为201215126的学生数据

delete from student where sno='201215126';

②删除所有的学生选课记录

delete from sc;

③删除计算机科学系所有学生的选课记录

delete from sc where sno in (select  sno from student where sdept='cs');

4、空值
空值就是“不知道”或“不存在”或“无意义”的值。

0x04 视图

1、定义视图
①建立信息系学生的视图,并要求进行修改和插入操作。

create view is_student as select sno,sname,sage from student where sdept='is' with check option;
#with check option使得视图能够进行增删改查等操作

②建立信息系选修了1号课程的学生的视图(包括学号,姓名,成绩)

create view is_s1(sno,sname,grade) as select student.sno,sname,grade from student,sc where sdept='is' and student.sno=sc.sno and sc.cno='1';

③定义一个反映学生出生年份的视图

create view bt_s(sno,sname,sbirth) as select sno,sname,2014-sage from student;

④将学生的学号及平均成绩定义为一个视图

create view s_g(sno,gavg) as select sno,avg(grade) from sc group by sno;

2、删除视图
①删除视图

drop view is_s1 cascade;
#使用联级删除

3、查询视图
查询视图与查询基本表相同。
①在信息系学生的视图中找出年龄小于20岁的学生。

select sno,sage from is_student where sage<20;

4、更新视图
①将信息系学生视图is_student中学号“201215122”的学生姓名改为“刘晨”。

update is_student set sname='刘晨' where sno='201215121';

②向信息系学生视图插入一个新的学生记录

insert into is_student values('201215127','王五',20);

③删除信息系学生视图is_student中学号为“201215127”的记录

delete from is_student where sno='201215127';
原文地址:https://www.cnblogs.com/observering/p/13783914.html