数据库(三)关系数据库标准语言SQL(1)

来源:互联网 发布:软件会员卡积分下载 编辑:程序博客网 时间:2024/05/16 07:10

SQL的概述

1.综合统一

综合了定义语言DDL、操作语言DML、控制语言DCL.

2.高度非过程化

只需提出做什么,无需指明怎么做。

3.面向集合的操作方式

4.以同一种语法结构提供多种使用方式

SQL既是独立语言,又是嵌入式语言。

5.语言简洁,方便使用



数据定义

学生表
create table Student    (Sno char(9) primary key,    主码     Sname char(20) unique,      取值唯一
     Ssex char(2),
Sdept chat(20) Sage smallint, );
课程表
create table Course    (Cno char(4) primary key,      Cname char(40) not null, 非空值      Cpne char(4),      Ccredit smallint,      foreign key(Cpno) referances Course(Cno) 外码     );
学生选课表
create table SC    (Sno char(9),     Cno char(4),     Grade smallint,     primary key (Sno,Cno), 主码由两个属性构成     foreign key (Sno) referance Student(Sno), 外码及参照     foreign key (Cno) referance Course(Cno),    )

修改表
alter table Student add ruxueshijan date; 加入入学时间列,类型为date
alter table Student alter column Sage int; 将原来年龄列的类型由char*改为intalter table Coures add unique(Cname); 将课程名增加取值唯一的约束
删除表
drop table Student cascade; 无限制删除,删除所有索引、触发器、引用该表的视图和表。drop table Student restrict; 有限制删除
索引
create index [唯一unique][聚簇cluster]<索引名> on <表名>(属性名,[升序asc(默认)][降序desc])cerate unique index SCno on SC(Sno asc,Cno desc)

数据查询

单表查询

select中选项

查询经过计算的值并重命名(用空格隔开)

select Sname, 2014-Sage birthday from Student;

改大小写

lower(属性名)

去重

[所有行all(默认)][去重distinct],作用于所有目标列

where中选项

1.比大小  

 =,>,<,>=,<=,!=,<>,!>!<

2.确定范围

 between ...and.... 包括端点值

3.确定集合

select Sname from Student where Sdep not  in ('CS','MA');  查询院系不为cs和ma的学生姓名

4.字符匹配

where Sname like '刘%';  姓刘where Sname like '刘_ _';  姓刘且全名三字

5.确定空值

where Grade is (not) null;

6.多重条件

and 优先级高于or ,可用小括号()改变优先级

集函数

计数count   求和sum    平均值avg    最大max   最小min
对列的集操作,可加入上述去重
只能用于select 和分组后的having语句

分组

group by分组 having限定
select Sno from SC where Score>90 group by Sno having count(*)> 3; 选出选了三门以上课且有一门课高于90分的学生学号
选出选了三门以上课且所有课都及格的学生的学号
select Sno from SC group by Sno having(min>=60 and count(*)>=3 )
选出选了三门以上课且三门以上及格的学生的学号
select Sno from SC where Grade>=60 group by Sno having( count(*)>=3 );












0 0