完整性约束:
http://www.cnblogs.com/linhaifeng/articles/7238814.html
约束条件与数据类型的宽度一样,都是可选参数
作用:用于保证数据的完整性和一致性
主要分为:
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...)
重点:
1.not null与default
2.unique
3.primary key
4.auto_increment
5.foreign key
一、not null与default
not null - 不可空
null - 可空
默认值,创建列时可以指定默认值,当插入数据时如果未主动设置,则自动添加默认值
create table tb1(
nid int not null defalut 2,
num int not null
)
![]()
1 ==================not null====================
2 mysql> create table t1(id int); #id字段默认可以插入空
3 mysql> desc t1;
4 +-------+---------+------+-----+---------+-------+
5 | Field | Type | Null | Key | Default | Extra |
6 +-------+---------+------+-----+---------+-------+
7 | id | int(11) | YES | | NULL | |
8 +-------+---------+------+-----+---------+-------+
9 mysql> insert into t1 values(); #可以插入空
10
11 mysql> create table t2(id int not null); #设置字段id不为空
12 mysql> desc t2;
13 +-------+---------+------+-----+---------+-------+
14 | Field | Type | Null | Key | Default | Extra |
15 +-------+---------+------+-----+---------+-------+
16 | id | int(11) | NO | | NULL | |
17 +-------+---------+------+-----+---------+-------+
18 mysql> insert into t2 values(); #不能插入空
19 ERROR 1364 (HY000): Field 'id' doesn't have a default value
20
21 ==================default====================
22 #设置id字段有默认值后,则无论id字段是null还是not null,都可以插入空,插入空默认填入default指定的默认值
23 mysql> create table t3(id int default 1);
24 mysql> alter table t3 modify id int not null default 1;
25
26 ==================综合练习====================
27 mysql> create table student(
28 -> name varchar(20) not null,
29 -> age int(3) unsigned not null default 18,
30 -> sex enum('male','female') default 'male',
31 -> hobby set('play','study','read','music') default 'play,music'
32 -> );
33 mysql> desc student;
34 +-------+------------------------------------+------+-----+------------+-------+
35 | Field | Type | Null | Key | Default | Extra |
36 +-------+------------------------------------+------+-----+------------+-------+
37 | name | varchar(20) | NO | | NULL | |
38 | age | int(3) unsigned | NO | | 18 | |
39 | sex | enum('male','female') | YES | | male | |
40 | hobby | set('play','study','read','music') | YES | | play,music | |
41 +-------+------------------------------------+------+-----+------------+-------+
42 mysql> insert into student(name) values('egon');
43 mysql> select * from student;
44 +------+-----+------+------------+
45 | name | age | sex | hobby |
46 +------+-----+------+------------+
47 | egon | 18 | male | play,music |
48 +------+-----+------+------------+
not null与default