sql語言基礎筆記
阿新 • • 發佈:2018-12-12
SQL語言基礎
SQL(Structured Query Language)結構化查詢語言。
SQL語言的分類
- 資料查詢語言(DQL):用於檢索資料庫中的資料,主要是SELECT語句。
- 資料操縱語言(DML):用於改變資料庫中的資料,主要是INSERT、UPDATE、DELETE 3條語句。
- 資料定義語言(DDL):用於建立、修改和刪除資料庫物件,主要是CREATE、ALTER、DROP 語句。
- 資料控制語言(DCL):用於執行許可權授權和許可權回收操縱,主要包括GRANT和REVOKE 兩條命令。
- 事物控制語言(TCL):用於維護資料的一致性,包括COMMIT、ROLLBACK和SAVEPOINT 3條語句。
SQL語言的編寫規則
- SQL關鍵字不區分大小寫,既可以使用大寫格式,也可以使用小寫格式,或者大小寫格式混用。
- 物件名和列名不區分大小寫,它們既可以使用大寫格式,也可以使用小寫格式,或者大小寫格式混用。
- 字元值區分大小寫。當在SQL語句中引用字元值時,必須給出正確的大小寫資料,否則不能得出正確的查詢結果。
建立表:
注意針對不同的資料庫,資料型別可能不一樣,使用之前可以先檢視以下
create table student //create table [表名] ( sno char(5) primary key not null , //列名 資料型別 完整性約束條件 sname varchar2(20) not null, ssex char(2) not null, sage int, sdept varchar2(20) ); create table course ( cno char(3) not null primary key, cname varchar2(20) not null, cpno char(3), credit int ); create table sc ( sno char(5) not null, cno char(3) not null, score int, primary key(sno,cno), foreign key(sno) references student(sno), foreign key(cno) references course(cno) );
以查詢方式建表:
create table student_infor( sname,ssex)
as
select sname,ssex
form student;
insert into student_infor
select * from student
where sage>10;
修改表:
alter table [表名] modify [列名] [資料型別] [約束] 修改原有列定義 add 【列名】 【資料型別】 【約束】 drop constraint 【完整性約束名】 drop column 【列名】 例如: alter table student drop column scome;
索引
create unique index [索引名]
on [表名] (【列名】【ASC|DESC】...); asc 預設值,表升序
create unique index index_sname on student(sname);
刪除索引:
drop index index_sname;
查詢
select sno,sname,ssex,sage,sdept from student;
select * from student;
select sno,sname
form student
where not sage >=20 and sdept in ('IS','MA','CS');
select sno,min(sage),max(sage),count(*)
from student
where cno='003'
order by score desc
select count(distinct sno)
from student
多表查詢:
select student.sno,sname,cname,score
from student,sc,course
where student.sno=sc.sno and sc.cno=course.cno
巢狀查詢:
select sname
from student
where sno in
( select sno from sc
where cno='002');
select sname
from student,sc
where student.sno=sc.sno and cno='002';
資料更新:
insert into course(cno,cname,credit)
values('001','資料結構',4);
update course
set cname='資料結構‘
where cno='001';
delete from course
where cno='001';
檢視:
create view cs_student
as
select sno,sname,sage
from student
where sdept='CS';
select *
from cs_student
where sage<20;
drop view cs_student;
許可權控制:
grant select ,update(sno)
on sc
to public;
許可權回收:
revoke update(sno)
on sc
from public;