一、一致性
一致性包括not null、unique、check a)Not null name varchar(20) not null b)Unique 如果A1, A2...等构成了候选键,可以用unique(A1, A2...)来保证其唯一性,但这些字段仍然可为空,而为空值与任何值都不相等。 c)Check 限制semester的值: check (semester in (’Fall’, ’Winter’, ’Spring’, ’Summer’) d)Referential Integrity参照完整性 如果course.dept_name作为外键引用department表,为了保证course.dept_name的取值都存在于department.dept_name,添加参照完整性约束为: e)foreign key (dept name) references department二、数据类型和Schemas a)Date和time SQL标准规定的time相关类型有: date ’2001-04-25’ time ’09:30:00’ timestamp ’2001-04-25 10:29:01.45’ 字符串形式的日期可以使用cast e as t的方式来转换;也可以使用extract year/month/day/hour/minute/second from d的方式来单独提取年月日等数据; 还有current_day, current_timestamp(包含时区), localtimestamp(不包含时区的本地时间); interval类型表示时间的差 b)Default value create table student (ID varchar (5), name varchar (20) not null, dept name varchar (20), tot_cred numeric (3,0) default 0, primary key (ID)); 这里设置了tot_cred的默认值为0 c)创建索引 create index studentID index on student(ID)表示创建了名为studentID的索引,有的数据库产品又进一步区分了聚集索引(clustered)与非聚集索引(nonclustered) d)大对象类型Large-Object Type 如果要存储声音、图像等数据,数据量可能为KB甚至MB, GB级别,为此SQL提供了两种大对象类型 clob(character large object)和blob(binary...)。不同数据库的具体实现会有区别,而且实际使用中不推荐使用这些类型,而往往将数据保存在文件系统,并在数据库保存其存放位置。 e)用户自定义类型 允许基于现有的类型来自定义数据类型,比如: create type Dollars as numeric(12,2); create type Pounds as numeric(12,2); 自定义类型Dollars和Pounds虽然都是numeric(12,2)类型,但在业务上被认为是不同的数据类型。 还有一种定义方式为: create domain DDollars as numeric(12,2) not null; type和domain的细微的区别在于domain可以同时添加约束如not null,;而且domain也不是完全的强类型,只要值是兼容的,就可以赋值给domain定义的类型,而type却不行。 e)Create table的扩展 create table temp instructor like instructor;创建了一个与sinstructor有相同结构的表 在编写SQL时,有时会创建临时表并存入数据,这时可以用简化写法: create table t1 as (select * from instructor where dept name= ’Music’) with data; t1表结构与查询结果集相同,如果去掉with data,则只创建schema而不插入数据。三、授权 权限控制可以针对用户或角色进行数据操纵、schema更新等的控制。 a)分配、撤销授权 分配权限的语法为: grant <privilege list> on <relation name or view name> to <user/role list>; privilege list包括select, insert, update, delete 对于update,可以设定允许更新某些属性: grant update (budget) on department to Amit, Satoshi; 类似地,撤销授权语法为: revoke <privilege list> on <relation name or view name> to <user/role list>; b)角色 基于角色的权限控制不是SQL的专利,很多共享型应用都采用这种授权方式。 create role instructor; grant select on takes to instructor; grant dean to Amit; 前面的语句创建了角色instructor,为期分配select from takes权限,然后将Amit归入instructor角色。在Amit执行查询前,SQL根据它所属角色具有的权限来做控制。 c)关于schema的授权 因为外键会影响后续的更新、删除等操作,所以有必要为外键的创建做权限控制: grant references (dept name) on department to Mariano; 学习资料:Database System Concepts, by Abraham Silberschatz, Henry F.Korth, S.Sudarshan