插入數據
插入元組
插入元組是指將新的元組插入指定表中。
語句格式爲:
insert into <表名>[<屬性列1>,<屬性列2>…]
values([<常量1>,<常量2>…])
例:將一個新學生元組(學號:2014213000,;姓名:Larry;性別:男;所在系:CS)插入到Student表中
**insert into** Student(Sno,Sname,Ssex,Sdept) **values**('2014213000','Larry','男','CS');
如果元組的每一個屬性都要插入新值,那麼可以省略表名後面的屬性列表
例:將一個新學生元組(學號:2014213000,;姓名:Larry;性別:男;所在系:CS,年齡:21)插入到Student表中
insert into Student values('2014213000','Larry','男','CS',21);
插入子查詢結果
例:對每一個系,求學生的平均年齡,並把結果存入數據庫
首先在數據庫中建立一個新表,其中一列存放系名,另一列存放相應的學生平均年齡
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;
修改數據
其功能是修改指定表中滿足where子句條件的元組。
其語句格式爲:
update <表名> set <列名>=<表達式>[,<列名>=<表達式>]
[where<條件>];
修改某一個元組的值
例:將學生2014213000的年齡改爲22歲
update Student set Sage = 22
where Sno = '2014213000';
修改多個元組的值
例:將所有的學生的年齡都加一歲
uodate Student set Sage = Sage + 1;
帶子查詢的修改語句
例:將計算機系全體學生的成績置零
update SC set Grade = 0
where Sno in(
select Sno
from Student
where Sno = SC.Sno and Sdept = 'CS'
);
或者爲:
update SC set Grade = 0
where 'CS' = (
select Sdept
from Student
where Student.Sno = SC.Sno
);
刪除數據
刪除語句的格式爲:
delete from <表名>
[where<條件>];
刪除某一個元組的值
例:刪除學號爲2014213000的學生記錄
delete from Student where Sno = '2014213000';
刪除多個元組的值
例:刪除所有學生的選課記錄
delete from SC;
帶子查詢的刪除語句
例:刪除計算機系所有學生的選課記錄
delete from SC
where Sno in(
select Sno
from Student
where Sno = SC.Sno and Sdept = 'CS'
);