SQL练习4 数据更新 数据库系统概论第五版 王珊

1.插入数据

1.1插入元组

1 格式
insert into<表名>[<属性列1>,<属性列2>...]
values (<常量1>,<常量2>...)

3.69 将一个新学生元组(学号:201215128,姓名:陈冬,性别:男,所在系:IS,年龄:18)插入到Student表中

insert into Student(Sno,Sname,Ssex,Sdept,Sage)
values('201215128','陈冬','男','IS',18);

3.70 将学生张成民的信息插入到Student表中
insert into Student
values('201215126','张成民','男',18,'CS');

3.71插入一条选课记录('201215128','1');
insert into sc(Sno,Cno)
values('201215128','1');
-- 为grade列自动插入空值

insert into sc
values('201215128','1',null);

1.2插入子查询结果

insert
into <表名>[<属性列1>,<属性列2>..]
子查询;

3.72 对每一个系,求学生的平均年龄,并把结果存入数据库
首先在数据库中建立一个新表,其中一列存放系名,另一列存放相应的学生平均年龄.
create table Dept_age
	(Sdept char(15), -- 逗号不能忘
	Avg_age smallint);
然后对Student表按系分组求平均年龄,再把系名和平均年龄存入新表中
insert
into Dept_age(Sdept,Avg_age)
select Sdept,AVG(Sage)
from student
group by Sdept;

2.修改数据

2.1修改某一个元组的值

3.73 将学生201215121的年龄改为22update student
set Sage = 22
where Sno='201215121';

2.2修改多个元组的值

3.74 将所有学生的年龄增加一岁
update student
set Sage = Sage+1;

2.3带子查询的修改语句

3.75 将计算机科学系全体学生的成绩置0
update SC
set Grade = 0
where Sno in
	(select sno
	from Student
	where Sdept='cs');

3.删除数据

格式:
delete
from <表名>
[where <条件>]

3.1删除某一个元组的值

3.2删除多个元组的值

3.3带子查询的删除语句

3.76 删除学号为201215128的学生记录
delete
from student
where Sno='201215128';

3.77  删除所有学生的选课记录
delete
from SC;

3.78 删除计算机系所有学生的选课记录
delete 
from SC
where Sno
	(select Sno
	from Student
	where Sdept='CS');

原创文章 36 获赞 8 访问量 2771

猜你喜欢

转载自blog.csdn.net/qq_41398619/article/details/105467957