1. 约束
为了防止不符合规范的数据进入数据库, 在用户对数据进行插入, 修改, 删除等操作时, DBMS 自动按照一定的约束条件对数据进行监测, 使不符合规范的数据不能进入数据库, 以确保数据库中存储的数据正确, 有效.
约束条件与数据类型的宽度一样, 都是可选参数
作用: 用于保证数据的完整性和一致性
主要分:
PRIMARY KEY (PK) 标识该字段为该表的主键, 可以唯一的标识记录
FOREIGN KEY (FK) 标识该字段为该表的外键
NOT NULL 标识该字段不能为空
UNIQUE KEY (UK) 标识该字段的值是唯一的
AUTO_INCREMENT 标识该字段的值自动增长 (整数类型, 而且为主键)
DEFAULT 为该字段设置默认值
UNSIGNED 无符号
ZEROFILL 使用 0 填充
1. 是否允许为空, 默认 NULL. 可设置 NOT NULL, 字段不允许为空, 必须赋值
2. 字段是否有默认值, 缺省的默认值是 NULL, 如果插入记录时不给字段赋值, 此字段使用默认值
sex enum('male','female') not null default 'male'
age int unsigned NOT NULL default 20 必须为正值 (无符号) 不允许为空 默认是 20
3. 是否是 key
主键 primary key
外键 foreign key
索引 (index,unique...)
2.nou null 和 default
一般二者是连用的, 不允许为空, 当没有传的时候就用默认值填充.
- create table tb1(
- nid int not null defalut 2,
- num int not null
- )
- 3.unique
- create table service(
- id int primary key auto_increment,
- name varchar(20),
- host varchar(15) not null,
- port int not null,
- unique(host,port) #联合唯一
- );
- MySQL> insert into service values
- -> (1,'nginx','192.168.0.10',80),
- -> (2,'haproxy','192.168.0.20',80),
- -> (3,'mysql','192.168.0.30',3306)
- -> ;
- Query OK, 3 rows affected (0.01 sec)
- Records: 3 Duplicates: 0 Warnings: 0
- MySQL> insert into service(name,host,port) values('nginx','192.168.0.10',80);
- ERROR 1062 (23000): Duplicate entry '192.168.0.10-80' for key 'host'
- create table user_tb(
- id int,
- username varchar(32) not null,
- num int not null,
- unique(username,num)
- );
- create table user_tb(
- id int,
- username varchar(32) not null,
- num int not null,
- primary key(username,num)
- );
- View Code
- 5. auto_increment
来源: http://www.bubuko.com/infodetail-3209461.html