Mysql列约束,字段属性.docx
文本预览下载声明
NULL属性空约束mysql的NULL不是数据,也不是类型!只是标识属性!用于说明某个字段,是否可以为null (是否可以什么都不存)NULL采用关键字 NULL表示(不是字符串),是 NULL ,不是 NULL属性 null 表示可以为空 , not null 表示不能为空create table preperty_null_1 (id int,name varchar(10) null);insert into preperty_null_1 values (1,null);create table preperty_null_2 (id int,name varchar(10) not null);insert into preperty_null_2 values (1,null);如果,在添加数据时,没有指定值,也会是NULL!default属性,默认值约束采用 default 关键字,来限定一个字段的默认值,在没有指定字段数据时,采用默认值!create table preperty_default_1 (id int,name varchar(10) default gin);insert into preperty_default_1 (id) values (1);default 与 null 的处理关系 :如果此时,该字段被指定了一个 null :不能使用默认值 ,允许为 null 则为 null,不允许则插入失败!如果一个字段没有指定默认值,那么默认为NULL此时,如果在定义该字段时,不允许为 NULL !则插入时,必须要保证该处有值才可以!(另外一个选择是指定默认值)默认值 ,存在一些特殊的标记关键字:default , 用在值中的关键字current_timestamp,用在第一个时间戳类型的字段上,用于表示当前的时间:典型的在很多表上增加一个 update_time 将其默认值设置成 current_timestamp 。就可以记录下当前时间主键约束 / 唯一约束 (primary / unique)站在约束的角度,限制的,该字段,值要唯一!但是主键 与 唯一 不是一个概念!都是索引的一种!主键:可以唯一标识记录的字段,称之为主键!但是一个表,只能有一个主键!典型的,在创建表时,主动增加一个非实体的自然属性,充当主键,采用整型,运算速度更快!其他的唯一字段,建立唯一约束!如何建立:两种方案第一种方案:create table preperty_primary_1 (id int primary key,sn char(5),name varchar(10));第二种方案:create table preperty_primary_2 (id int,sn char(5),name varchar(10),primary key (id));一旦创建了主键:默认就是不能为空:唯一:保证在某个字段上的数据是唯一的,可以设置成唯一约束!创建唯一:create table preperty_unique_1 (id int primary key,sn char(5) unique,name varchar(10));create table preperty_unique_2 (id int primary key,sn char(5),name varchar(10),unique key (sn));一个表可以有多个唯一,但是只能有一个主键!注意:主键或者是唯一,都可以由多个字段组成!create table preperty_primary_3 (id int,sn char(5),name varchar(10),primary key (id,sn));因此,主键与字段的概念:是由字段来充当主键,不是字段就是主键!(称之为复合主键)尽量采用 id 一个来作为主键!create table preperty_unique_3 (id int,sn char(5),name varchar(10),unique key (id,sn));如果管理主键与唯一:删除主键:语法:alter table tb_name drop primary key;添加主键:语法:alter table tb_name add primary key(字段列表);删除唯一:语法:alter table tb_name drop index index_name;可以使用 show create table tb_name; 语句来查看唯一的索引名称:如果删除索引名为id的唯一,语法如下:alter table preperty_unique_3 drop index id;添加唯一:语法:alter table tb_
显示全部