总结:
1,not null 不能插入空,不设置可空
2,unique 单列唯一
create table department(name char(10) unique); 创建方式一
create table department( unique(name)); 创建方式二
联合唯一: unique(name) unique(id) 两个都不同才可插入
组合唯一:unique(name,id) 有一个不同即可插入
3,主键 primary key = not null unique
作用:唯一标识,查询优化.
复合主键: 有一个不同即可.
注意 : 多列主键有问题
4,auto_increment(自增长)
# 步长auto_increment_increment,默认为1
# 起始的偏移量auto_increment_offset, 默认是1
# 设置步长 为会话设置,只在本次连接中有效
set session auto_increment_increment=5;
#全局设置步长 都有效。
set global auto_increment_increment=5;
# 设置起始偏移量
set global auto_increment_offset=3;
清空表区分delete和truncate的区别:
delete from t1; #如果有自增id,新增的数据,仍然是以删除前的最后一样作为起始。
truncate table t1;数据量大,删除速度比上一条快,且直接从零开始。
5,foreign key:
constraint fk_dep foreign key(dep_id) references dep(id)
名字 从表 关联 主表
on delete cascade #同步删除
on update cascade #同步更新
加上可直接删除,不用先删除从表,再删主表;
直接删除主表,从表中的数据也会删除.
not null 与 default
- unique
- primary
- auto_increment
- foreign key
约束条件与数据类型的宽度一样,都是可选参数
作用:用于保证数据的完整性和一致性
主要分为:
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'
#必须为正值(无符号) 不允许为空 默认是20
age int unsigned NOT NULL default 20
# 3. 是否是key
主键 primary key
外键 foreign key
索引 (index,unique...)
二、not null 与default
是否可空,null表示空,非字符串
not null - 不可空
null - 可空
默认值,创建列时可以指定默认值,当插入数据时如果未主动设置,则自动添加默认值
create table tb1(
nid int not null defalut 2,
num int not null
);
验证1:
mysql> create table t11(id int);# id字段默认可以为空 Query OK, 0 rows affected (0.05 sec) mysql> desc t11; +-------+---------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-------+---------+------+-----+---------+-------+ | id | int(11) | YES | | NULL | | +-------+---------+------+-----+---------+-------+ 1 row in set (0.03 sec) mysql> insert into t11 values(); #给t11表插一个空的值 Query OK, 1 row affected (0.00 sec) #查询结果如下 mysql> select * from t11; +------+ | id | +------+ | NULL | +------+ 1 row in set (0.00 sec)