数据的更新
1.创建数据库后创建表格
CREATE TABLE Student(
Sno char(9) not null,
Sname char(20),
Ssex char(2),
Sage smallint,
Sdept char(20)
primary key (Sno)
);
CREATE TABLE Course(
Cno char(4) not null,
Cname char(40),
Cpno char(4),
Ccredit smallint,
primary key (Cno)
);
CREATE TABLE SC(
Sno char(9) not null,
Cno char(4) not null,
Grade smallint,
constraint pk_SC primary key(Sno,Cno),
foreign key (Sno) references Student(Sno),
foreign key (Cno) references Course(Cno),
);
2.使用insert语句向表格添加数据
(1)插入元组
插入元组有两种语法,一种是指定列,另一种不指定列,只指出表名,表示新元组要在表的所有的属性列上都指定值,此需与建表时的次序相同,values子句中的值与属性列要一一对应,不然会因为数据类型不匹配可能出错
INSERT
INTO<表名>[(<属性列1>[,<属性列2>],.....)]
VALUES(<常量1>[,<常量2>].....)
--INSERT INTO Student(Sno,Sname,Ssex,Sage,Sdept)
--VALUES(201215121,\'李勇\',\'男\',20,\'CS\')
--INSERT INTO Student(Sno,Sname,Ssex,Sage,Sdept)
--VALUES(201215122,\'刘晨\',\'女\',19,\'CS\')
INSERT INTO Student(Sno,Sname,Ssex,Sage,Sdept)
VALUES(201215123,\'王敏\',\'女\',18,\'MA\');
INSERT INTO Student(Sno,Sname,Ssex,Sage,Sdept)
VALUES(201215125,\'张立\',\'男\',19,\'IS\');
insert into Course values(1,\'数据库\',5,4);
insert into Course values(2,\'数学\',null,2);
insert into Course values(3,\'信息系统\',1,4);
insert into Course values(4,\'操作系统\',6,3);
insert into Course values(5,\'数据结构\',7,4);
insert into Course values(6,\'数据处理\',null,2);
insert into Course values(7,\'PASCAL语言\',6,4);
insert into SC VALUES(201215121,1,92);
insert into SC VALUES(201215121,2,85);
insert into SC VALUES(201215121,3,88);
insert into SC VALUES(201215122,2,90);
insert into SC VALUES(201215122,3,80);
(2)插入子查询结果
子查询可以用于嵌套在insert语句中,生成要插入的批量数据
例如:对每一个系,求学生的平均年龄,并将结果放入数据库中
--首先建立新的表存放数据:
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;
3.修改表格数据
一般格式:
update<表名>
set<列名>=<表达式> [,<列名>=<表达式>]...
[where<条件>];
(1)修改某一元组
update Student
set Sage=22
where Sno=\'201215121\';
(2)修改多个元组
--将所有的学生年龄都增加一岁
update Student set Sage = Sage+1;
(3)带子查询的修改语句
将CS专业的全体学生成绩置为100
update SC set Grade=100
where Sno IN(select Sno from Student where Sdept=\'CS\');
4.删除数据
一般格式:delete from<表名>[where <条件>];
(1)删除某个元组的值
delete
from Student where Sno=\'201215128\';
(2)删除多个元组的值
删除所有课程
delete from Course;
(3)带子查询的删除语句
delete from SC
where Sno IN(select Sno from Student where Sdept=\'CS\');