我们所说的数据更新就包括:插入,修改,删除三种。
实验环境:SQLliteStudio
实验数据表:
- Student(Sno, Sname, Ssex, Sage, Sdept) 学生信息表
- Course(Cno, Cname, Cpno, Ccredit) 课程表
- SC(Sno, Cno, Grade) 学生选课表
1. 插入数据
关键字 Insert
插入单个元组格式:
insert into <table_name> values(<col_value>,...) where <condition>
插入一个新的选课记录:
insert into sc values('0980',1,98.5);
需要注意的是完整性校验,比如说有的是不能为空值的,但是在value那里写上了null,那就会报错了。
2. 修改数据
关键字 update
格式:
update <tabel_name> set <col_name>=<new_value> where <condition>
例子:
把学号是95001的年龄修改为22岁
update student set sage=22 where sno='95001'
和insert不同的是update 语句可以使用子查询条件的,比如说把CS系的学生的成绩全部置0
update sc set grade=0 where sno in (select sno from student where sdept='CS')
方法2 :
update sc set grade=0 where 'cs'=(select Sdept from student where Student.sno=SC.sno);
3. 删除数据
关键字delete
格式:
delete from <table_name> where <condition>
删除学号是9910的学生信息:
delete from student where sno='9910'
删除学号是9910的学生的2号课程选课记录:
delete from sc where sno='9910' and cno=2
删除计算机系的所有学生的选课记录:
delete from sc where sno in(select sno from student where sdept='cs')
假如我们需要删除整个表:
delete from <table_name>
但是一般我们都不这样操作,因为他是一行行删除的,但是使用:
truncate table <table_name>
是直接删除整个表,再创建一个新表。