MySQL 列约束

1 NULL/NOT NULL

create table t_1(
a int not null;
b int);

insert into t_1 (a) values (10);//只插入a,b表示为null。

2 默认值属性

通过default value 来声明,没有赋值,选择默认值。

create table t_2(
a int not null default 10,
b int not null default 21
);

默认值,在没有为该字段设置值是启用。而且默认值的设置固定值,常见的是,一个字段不能为空,而且存在默认值。

3 主键,唯一索引

主键:PK primary key,可以唯一标识,其余记录的字段或者是字段的集合,就是主键

主键可以是真实实体的属性,但是常用的获得解决方案是:

利用一个与实体信息不相关的属性,作为唯一标识,主键与业务逻辑不发生关系,只用来标识记录,设置逐渐的语法:primary key完成:1)在字段上设置 2)在定义完字段之后,可以加主键。

1) 在字段上设置

create table t_3(
t_id int primary key,
t_name varchar(5),
class_name varchar(6),
days tinyint unsigned
);

2) 定义完字段之后加主键

create table t_4(
t_id int,
t_name varchar(5),
class_name varchar(6),
days tinyint unsigned,
primary key (t_id)
);

4 自动增长

为每条记录提供一个唯一的表示,每次插入记录时,将某个字段的值自动加1,使用auto_increment标识,需要整型,还需要有索引,可以选择NULL或者不插入数据。

create table t_4(

t_id int primary key auto_increment,

t_name varchar(5),

class_name varchar(6),

days tinyint unsigned);

insert into t_4 values (null,'Li','0228',34);

自动增长的初始值,是可以设置的, 默认是1,通过表的选项:auto_increment n 改变初始值。

alter tablet_4 auto_increment 10;

猜你喜欢

转载自blog.csdn.net/yummy_lym/article/details/82748361