SQL语言特点:一体化;高度非过程化;面向集合的操作方式;提供多种方式使用;语言简洁。
SQL支持的数据类型:数值型、日期时间型、字符串型、二进制串、其他类型。
SQL功能:数据定义(DDL)、数据查询(DQL)、数据操纵(DML)、数据控制(DCL)。
DDL
创建:create database 数据库名 create table 表名
修改:alter database 数据库名 alter table 表名
删除:drop database 数据库名 drop table 表名
约束
非空约束:NOT NULL
主键约束 表级: primary key(列名,...)
列级: primary key
外键约束:[foreign key 列名] references 外表名(外表列名)
唯一值约束 表级:unique[(列名,...)]
列级:unique
默认值约束:default 常量表达式 [for 列名]
列取值范围约束:check(逻辑表达式)
DQL
单表查询:select 列名序列 from 表名 where 条件
输出结果是否重复:distinct | * 别名:表达式 as 列别名
where子句的查询条件
运算符:= > >= <= < <> !=
确定范围:列名 | 表达式 [not] between 上限值 and 下限值
确定集合:列名 [not] in(常量,...)
字符匹配:列名 [not] like 匹配串 '%' or '_'
空值:列名 is [not] null
逻辑谓词:and or
排序:order by 列名 [ASC | DESC]
分组:group by 分组依据 [having 组提取条件]
多表连接查询:from 表1 left | right | inner | full join 表2 on 连接条件 [join 表3 on 条件...]
top子句:top n [percent] [with ties]
case函数:
case 测试表达式
when 简单表达式1 then 结果表达式1
...
when 简单表达式n then 结果表达式n
else 结果表达式n+1
end
将查询结果保存到表:select 查询列表序列 into 新表名 from 数据源
where子查询:
1. where 列名 [not] in(子查询)
2. where 列名 比较运算符 some | all(子查询) #some也可换成any
3. where 列名 [not] exists(子查询)
in与some等价 not in与!=all等价
例:
1.(in)查找sc表学过C01和C02课程(cno)的学号(sno)
select sno from sc where cno='C01' and sno in(select sno from sc where cno='C02');
1.(some)查找sc表中C01课程的成绩(score)不是最低的所有学生的学号
select sno from sc where score>some(select score from sc where cno='C01') and cno='C01';
3.(not exists)查找至少学过(01号同学学过的所有课程)的同学的学号
select distinct sno from sc as s1 where not exists(select * from sc as s2 where s2.sno='01' and not exists(select * from sc where sc.cno=s2.cno and sc.sno=s1.sno));
查询的集合运算:并(union)、交(intersect)、差(except)。
视图:创建 create view 视图名
修改 alter view 视图名
删除 drop view 视图名
DML
单行插入:insert into 表名(列表名) values (值列表) #列名省略,需与定义的列名一致;若未省略,与语句中列名的顺序一致。
多行插入:insert into 表名(列表名) select 语句 #将查询的结果插入到表中。
数据更新:update 表名 set 列名=表达式 from 表名 where 条件
数据删除:delete from 表名 where 条件
DCL
授权:grant 权限 to 用户 #创建者向其他用户授予操作该对象的某些权限
回收授权:revoke 权限 from 用户 #数据库管理员或其他授权者回收指定用户对某个数据库对象的某种权限
拒权:deny 权限 to 用户 #拒绝为指定用户对某个数据库对象使用某种权限