1. 程式人生 > >SQL資料庫常用命令

SQL資料庫常用命令

建立資料庫

create database student;//建立一個名為student的資料庫

建立資料庫的表

create table student		//定義一個名為student的表
(
sno char(9)  primary key,				
sname char(20),
ssex char(2)  constraint s_check check(ssex in('男','女'))
);

修改基本表

alter table <表名>
add [column] <新列名><資料型別> [完整性約束]
add <表級完整性約束>
drop [column] <列名> [cascade|restrict]
drop constraint<完整性約束名> [cascade|restrict]
alter column <列名><資料型別>;
eg:向student表中增加'入學時間'列。
alter table student add student_time datetime;
eg:student表增加表級完整性約束。
alter table student add primary key(sno);
eg:student表刪除'入學時間'列;
alter table student drop column student_time;//注意在刪除時需要帶上column,增加時隨意。
eg:student表刪除使用者定義的完整性約束
alter table student drop constraint s_check;
eg:修改列的定義
alter table student alter column;

刪除基本表

drop table student ;

索引的建立、修改、刪除

create unique index <索引名> on <表名>(<列名> asc,<列名> desc,...)
alter index <索引名> rename to <新的索引名>
drop index <索引名>

資料查詢

select [all|distinct] <目標列表達式> 
from <表名或檢視名> 
[where <條件表示式>]
[group by <列名> [having <表示式>]  ]
[order by <列名> [asc|desc]  ]

常用的查詢條件
確定範圍: between and ;not between and
確定集合: in ;not in
字元匹配:like ; not like("_"表示單個任意字元;"%"表示任意長度的字串)
空值:is null;is not null
邏輯運算: and ; or ;not 
聚集函式
count(*)			統計元組個數
count([distinct|all] <列名>) 		統計一列中值的個數
sum() 、avg()、max()、min()
注意:聚集函式只能用於select子句和group by 中的having 子句

資料更新

insert into student(sno,sname)values('1','小王');
insert into student(sno,sname) 子查詢;

update <表名> set <列名>=<表示式> [where <條件>];

delete from <表名> [where <條件>];

檢視

create view <檢視名> (<列名>,<列名>,<列名>)
as 子查詢
[with check option]

插、刪、改 類似表