Welcome 微信登录

首页 / 数据库 / MySQL / Oracle 约束的基础知识介绍

1,约束的分类。约束分成5类:1. not null,2.primary key,3.check,4.unique,5.foreign key。1.1 not null约束默认情况下,所有列的值都可以包含null值,当在列上定义not null约束后,列上面就必须得有值。not null约束还常常与其它的约束一起组合起来使用,比如与unique约束一起使用,就可以保证新插入的列的数据不会与已经存在的数据发生冲突。需要在相当的列上面创建索引的时候,建议也在相关的列上面增加上not null约束,因为索引不会存放null记录。1.2 primary key约束主键约束其实就是not null约束与unique约束的一个组合,用来保证行记录的唯一,不重复性。每张表只能有一个主键约束,在表设计的时候,我们一般都每张表上面都要有主键约束。在创建主键的时候会自己的创建相应约束名的索引,在选择主键约束的列的时候可以参考下面指导:1.选择sequence的列做为主键。2.选择列的值是唯一的,并且没有null值的列。3.主键的更一般不会发生修改,也仅仅用于标识行的唯一性,不用于其它的目的。4.主键的列尽量选择值比较短的值或者是number的值。1.3 unique约束unique约束是保证值的记录不会出现相同的值,但是noll值不受权限,创建unique约束的时候,会自己创建约束名的索引。1.4 check约束检查约束用于检查值在插入时是否满足指定的条件,比如值要求大于10小于100.1.5 foreign key约束当2个表,当A表中的列的值必须在B表中的列的值时候,可以定义外键约束。父表相关的值上面有主键或者唯一性约束。不过很多公司要求不能使用外键,让开发自己用程序来判断。2,约束的定义约束可以在表创建的时候指定,也可以在表创建完成后通过alter命令来创建,下面是每一种约束创建的语法。
  1.   2.1 not null约束 
  2.  
  3.       create table test_cons (id number constraint cons_test_cons_id_nonull not null); 
  4.  
  5.       create table test_cons_1(id number not null); 
  6.  
  7.       alter table test_cons_2 modify id not null; 
  8.  
  9.       2.2 primary key 
  10.  
  11. create table test_cons_1 (id number primary key); 
  12.  
  13. create table test_cons_2 (id number constraint cons_2 primary key); 
  14.  
  15. create table test_cons_3 (id number,constraint cons_3 primary key(id)); 
  16.  
  17. create table test_cons_4 (id number); 
  18.  
  19. alter table test_cons_4 add constraint cons_4 primary key(id); 
  20.  
  21.     2.3 unique 
  22.  
  23. create table test_cons_1 (id number unique); 
  24.  
  25. create table test_cons_2 (id number constraint cons_2 unique); 
  26.  
  27. create table test_cons_3 (id number,constraint cons_3 unique(id)); 
  28.  
  29. create table test_cons_4 (id number); 
  30.  
  31. alter table test_cons_4 add constraint cons_4 unique(id); 
  32.  
  33.  2.4 check 
  34.  
  35. create table test_cons_1 (id number check (id > 10 and id <100)); 
  36.  
  37. create table test_cons_2 (id number constraint cons_2 check (id > 10 and id <100)); 
  38.  
  39. create table test_cons_3 (id number,constraint cons_3 check (id > 10 and id <100)); 
  40.  
  41. create table test_cons_4 (id number); 
  42.  
  43. alter table test_cons_4 add constraint cons_4 check (id > 10 and id <100); 
  44.  
  45. 2.5 外键约束 
  46.  
  47. create table test_cons_1 (id number,constraint cons_1 foreign key (id) references test_cons(id)); 
  48.  
  49. alter table test_cons_4 add constraint cons_4 foreign key (id) references test_cons(id); 
  • 1
  • 2
  • 下一页
Oracle复杂查询练习题Oracle 11gR2用exp无法导出空表的解决相关资讯      Oracle基础知识  Oracle约束 
  • Oracle约束的分类  (03/17/2015 19:28:41)
  • 查看Oracle 32位还是64位(x86 or   (10/05/2014 19:10:00)
  • Oracle数据库中由于没有做任何约束  (04/01/2014 17:27:56)
  • Oracle外键约束(Foreign Key)的  (12/06/2014 14:41:09)
  • Oracle约束Constraint对于CBO优化  (05/05/2014 19:49:38)
  • Oracle数据完整性约束:主键、外键  (10/27/2013 16:56:40)
本文评论 查看全部评论 (0)
表情: 姓名: 字数