SQL复习

SQL复习

创建表

create table SC (Sno char(9) primary key ,Cno char(4) not null , grade smallint unique,foreign key (Sno) reference Student(Sno));

修改表

>alter table SC add S_entrance Date; //增加属性和完整性约束条件
>alter table SC add Unique(S_entrance); //增加属性的完整性约束条件//
>alter table sc drop S_entrance //删除属性
>alter table sc alter column Stage int//将原Stage属性改为int

删除表

drop table Course

索引——提高查询速率

索引类型含义使用场景
Unique唯一索引,按此方式建立的索引只对应一个值经常修改的使用唯一索引
Cluster聚簇索引,索引项的顺序与表中记录的物理位置一致。采用B+树或hash索引因为聚簇索引与物理位置相关性强,所以经常修改的不适合用聚簇索引,因为增删改查意味着存储物理位置可能发生改变。经常查询的可用聚簇索引

create cluster index Studentname on Student(Sname);
drop index Studentname

查询

select [all | distinct ] <目标表达式1> [, <目标表达式2>] [, <目标表达式3>] …
from <表名或视图名> …
[where <条件>]
[group by <列名1> [having <条件表达式>]]
[order by <列名2> [asc | desc]

example
select Sno,Sname from Student
select * from Sudent
select Sname , Sage-2004 from Student


where <条件细节> examples
select Sname from Student where Sdept=”cs” ;
select Sname from Student where Sage<20
select Sname from Student where Sage (not) between 20 and 30;
确定集合:select Sname from Student where Sdept in (‘cs’,’math’,’pe’);
字符匹配: 语法:[not] like ‘<匹配串(可以是完整字符,也可以使用通配符%和_>’ [escape ‘<换码字符>’] ;

%和_解释:%:代表任意长度(长度可以为0) a%b : 以a开头以b结尾的字符串; _:代表任意单个字符 a_b 如 acb aeb;
such as select Sname from Student where Sname like “刘%” 区别 select Sname from Student where Sname like “刘_” 第一个为姓刘的,第二个为姓刘且名字为两个字的
select * from Course where Cname like DB%i_ _ :含义:查询以DB开头且倒数第三个为i的课程

select Sname from Student where Sage (not) between 20 and 30 order by Grade DESC , Sname ASC;
聚集函数: count sum avg max min
select AVG(Grade) from SC where Cno = 1;
select Sno from SC group by Sno having count(*) > 3 : 选修了3门以上课程的学生的学号
select Sname , Sage from Student where Sage < [ALL | ANY| EXIST](select Sage from Student where Sdept=”CS”); ALL:小于所有 ANY:只要小于其中一个即可; EXIST: 存在于
集合查询: UNION:并操作 INTERSECT:交操作
select Sno from SC where Cno=’1’ union select Sno from SC where Sno = ‘2’ : 查询既选修了1号课程也选修了2好课程的学生编

数据更新

insert into Student (Sno, Sname, Ssex , Sdept , Sage) values (‘2000102’,’张三’,’male’,’CS’,’18’);
update Student set Sage = 20 where Sno=’2000102’;
update Student set Sage = Sage +1 ;
delete from Student where Snp=’2000102’;

触发器

create trigger <触发器名>
example:

create trigger Insert_Or_Update_Sal //创建触发器
before insert or update on Teacher //在插入和更新表之前触发
for each row //行触发
as begin //触发具体动作
if(new.Job=’professor’) and (new.Sal<4000) then
new.Sal:=4000
end if ;
end;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值