MySQL 表的约束

114 阅读2分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第12天,点击查看活动详情

表的约束

1、非空约束

not null,一旦给某列加上not null,该列不能为null。

create table t1(
      a varchar(10) not null,
      b varchar(10)
   );
   insert into t1(a,b) values('111','222');  ok
   insert into t1(a,b) values('444',null);   ok
   insert into t1(a,b) values(null,'ddd');   error

2、设置字段的默认值

default 默认值

 create table t2(
      a int default 1001,
      b varchar(10) default 'hello'
   );
   insert into t2(a,b) values(100,'aaa');
   insert into t2(a) values(200);  b列会使用默认值
   select * from t2;

3、唯一性约束

unique key(uk),设置列不重复,唯一

   create table t3(
      a int unique key
   );          
   insert into t3(a) values(1);  ok
   insert into t3(a) values(1);  error

4、主键约束

primary key = pk,唯一并且不能为空 pk=uk+not null 一般每个表中至少有一列设置为主键

(1)单字段设置主键

create table t4(
      a int primary key 
    );
    insert into t4(a) values(100);   ok
    insert into t4(a) values(200);   ok
    insert into t4(a) values(null);  error
    insert into t4(a) values(100);   error

(2)多字段同时设置主键

 create table t5(
       a int,
       b int,
       c int,
       d int,
       constraint pk_name primary key(a,b,c)
    );

同时对多字段设置主键必须使用该方法设置。 对多个字段设置不能为空、唯一性约束以及默认值, 每个字段的后面分别加上即可:

   create table t6(
       a int not null,
       b int not null,
       c int unique key, 
       d int unique key,
       e int default 100,
       f int default 200
    );

5、设置字段自动增长

auto_increment 在插入数据的时候,字段上会自动生成唯一的序号,序号为整数类型。一般自动增加的属性是设置给主键字段的。 一个表中只能有一个字段加该属性。

   create table t7(
      a int primary key,
      b varchar(10)
   );
  insert into t7(b) values('aaa'); 默认a主键插入0
  insert into t7(b) values('bbb'); error,0违反唯一性约束了

   create table t8(
      a int primary key auto_increment,
      b varchar(10)
   );
 insert into t8(b) values('aaa'); 主键a默认从1开始自动增长
 insert into t8(b) values('bbb');  a插入的是2
 insert into t8(b) values('cc');  a插入的是3
 insert into t8(a,b) values(1001,'ddd'); a插入的1001
 insert into t8(b) values('fff');  a插入的是1002