数据库脚本知识总结
一,总共7种约束,1~4是表约束,5是列约束; 还有个默认的约束就无视了
1.<pk> 主键 Primary Key, 表中的一个或多个字段,它的值用于唯一地标识表中的某一条记录。
userID int primary key,
2.<fk> 外键 Foreign key, 表中的一个或多个字段,外部关键字的值与相关表的主关键字相匹配。
create table tOne
{
userID int primary key,
};
create table tTwo
{
CONSTRAINT 字段 FOREIGN KEY(userID, 其他字段...) REFERENCES tOne(userID, 其他字段...),
}
3.<uk> 唯一Unique key Constraint, 约束保证在一个字段或者一组字段里的数据与表中其它行的数据相比是唯一的。(就是不重复)
字段 char(12) unique,
4.<ck> 检查/校验 Check key Constraint, 用来检查字段所允许的范围。
constraint 字段 check(v1 > 4 and v1 < 8);
5. <not null> 非空,表示当前这个字段不能为空。
字段 int not null;
6.域约束 可以看做宏定义,替换所有表中需要用到相同的东西
语法如下:
create domain domain_name as
data type [default default_value]
[constraint constraint_name]
check(value condition expression)
例如:
create domain valid_no as
int constraint constraint_no
check(value between 100 and 999);
然后创建表时,使用valid_no域.
create table TestDomain (
emp_id valid_no,
emp_name varchar(10));
7.断言约束
语法如下: create assertion constraint_name check search condition 例如: create assertion assertion_name check(Emp_Sal.emp_id in(select emp_id from EmployeeInfo where emp_name is not null)); 添加断言后,每当试图添加或修改Emp_Sal表中的数据时, 就对断言中的搜索条件求值,如果为false,则取消执行,给出提示。
二、数据库操作
8.创建数据库
create basedata 数据库名;
9.创建表
create table 表名;
10.增删改查
alter table table_name add 字段 字段类型; /*对表增加字段*/
alter table table_name alter column 字段 类型; /*修改字段类型*/
alter table table_name add unique(字段); /*修改字段约束*/
drop table table_name cascade; /*如果有视图不会提醒,一并删除*/
drop table table_name restrict; /*如果有视图会提醒,阻止你删除*/
create [unique] [cluster] index 索引名 on 表名(字段[asc], ...); /*创建索引,默认升序排列;asc降序*/
drop index 索引名;
insert into 表名(对应字段) values(字段的值); /*插入*/、
update 表名 set 字段=表达式 + where 表达式; /*更新*/
delete from 表名 where 条件 /*删除一条记录*/
select [*/ distinct + 字段名] from 表名/视图 where 表达式 /*distinct 表示剔除相同值 */
[group by 字段 having 表达式] /*值相同在一组*/
[order by 字段 [asc | desc]] /*对字段排序*/
where 字段 in ("a","b","c"); /*查找范围,not in指范围之外*/
@字符匹配
[not] like '字符串' [escape '换码字符']
like '呵呵%';
like '呵呵_' 或者 like '呵呵__'; /*后者配备中文,中文两个字节,需要两个下划线*/
like 'data\_base' escape '\'; /*查找data_base, 遇到_ 进行转义,不会被认为字符串匹配功能*/
11.内连接
select 别名1.字段,别名2.字段 from 表 别名1,表 别名2 where 别名1.字段 = 别名2.字段
12.外连接
select 表.字段 from 表 left out join sc on (表.字段 = 表2.字段)
13.嵌套查询
where 字段 in (优先查找语句);
三、视图
create view 视图名(字段。。。) as 查询表达式 【with check option】 /*with check option 表示对视图进行操作*/
drop view 视图名 cascade;
四、触发器
语法:
create trigger 触发器名
[before | after] 触发事件 on 表名
for each [row | statement]
[when 触发条件]
触发动作
示例:
/*before*/
create trigger trigger_name
before insert or update on 表
for each row /*行及触发器*/
as begin
if (条件) then
new.字段 := 数值/字符串;
end if;
end;
删除触发器
drop trigger 触发器名 on 表;
浙公网安备 33010602011771号