数据库约束定义及分类

约束

约束定义及分类:

Constraint,对数据库中的数据做要求,以保证设计出来的数据库及其中的数据真实可用。

约束分为

  • 行完整性约束(三范式)
  • 列完整性约束。
  • 主键约束

Alter table 表名 add constraint PK_表名_列名 primary key(列名);

创建表时可以简写

Create table tt(ttid int primary key);

Create table tt(ttid int,primary key(ttid));

创建的主键名是PK_随机的十六进制代码

 

外键约束

外键约束是加在外键表中,外键表中也有主键。

Alter table 外键表 add constraint FK_外键表名_外键列 foreign key(外键列) references 主键表(主键列);

 

删除外键约束

alter table 表名 drop foreign key FK_表名_列名;

在创建表时还可以简写

Create table 表名(

T1id int primary key auto_increment,

Scid int,

Foreign key(scid) references 主表(主键列)

);

 

唯一约束

Alter table 表名 add constraint UQ_表名_列名 unique(列名);

在创建表时还可以简写

Create table 表名(

T1id int primary key auto_increment,

Scid int,

unique(列名)

);

 

默认值约束

Alter table 表名 alter 列名 set default 值;

  • 对于允许为空的列并且设置了默认值,插入时省略该列值为默认值;

Insert into 表名(主键[省略掉设置了默认值而且允许为空的列]) values(null);

  • 设置默认值,插入可以使用default关键字调用默认值;

Insert into 表名(主键,默认值列) values(null,default);

  • 插入时不要默认可以自由指定。

Insert into 表名(主键,默认值列) values(null,’其他值’);

创建表时又可以简写

Create table 表名(

默认值列 default 值

);

 

检查约束

Alter table 表名 add constraint CK_表名_列名 check(表达式);

ALTER table Student add constraint CK_Student_sname check(sname is not null);

 

创建表时可以简写

Create table Student(

Sname not null

);

 

Alter table Student add constraint CK_Student_sAge check(sAge>=18 and sAge<=60);

等同于

Alter table Student add constraint CK_Student_sAge check(sAge between 18 and 60);

 

MYSQL不知道检查约束!!

 

  • 对于由于操作系统或者浏览器外界元素的编码导致的乱码,在数据库中可以通过一个指令来纠正。

Set names 对应数据的编码;

Set character set 对应数据库的编码;

本文来自投稿,不代表科技代码立场,如若转载,请注明出处https://www.cwhello.com/2930.html

如有侵犯您的合法权益请发邮件951076433@qq.com联系删除

(0)
上一篇 2017年10月22日 22:28
下一篇 2017年10月24日 08:28

相关推荐

联系我们

QQ:951076433

在线咨询:点击这里给我发消息邮件:951076433@qq.com工作时间:周一至周五,9:30-18:30,节假日休息