sql语句中的约束
一、约束的定义
约束:用通俗易懂的话来说就是限制,为了保证数据的有效性,需要强制新添加的数据符合某种规范,否则不允许该数据添加进来。
二、约束类型
以创建表student为例
1、 not null 不允许为空
create table student(
id char(15) not null,
name varchar(24),
mobile char(11),
address varchar(120)
)
2、unique 唯一性 ,但是允许有多个null
create table student
id char(15) not null,
user_name varchar(18) unique,
password varchar(15)
)
3、primary key 主键,不允许为空且不允许重复
create table student(
id char(15) primary key,
name varchar(24),
mobile char(11),
address varchar(120)
)
4、auto_increment 自增长,只能用来使主键字段自动增加
create table student(
id int(3) primary key auto_increment,
name varchar(24),
mobile char(11),
address varchar(120)
)
5、default 默认值,如果没有为该字段指定值,则使用默认值
create table student(
id int(3) primary key auto_increment comment '主键',
name varchar(24) comment '姓名',
sex tinyint(1) default 0 comment '性别 0-男 1-女',
mobile char(11) comment '手机号码',
address varchar(120) comment '家庭地址'
)
补充:comment此处是在数据库表中起到了注释的作用,每个字段comment后面的内容都是对该字段的解释。