MySQL约束条件

default默认值

#补充知识点  插入数据的时候可以指定字段
create table test7(
    id int,
    name char(16));
insert into test7(name,id) values('yumo',1);

create table test8(
    id int,
    name char(16),
    gender enum('male','female','others') default 'male');
    
    insert into test8(name,id) values('huahua',1);
    insert into test8 values (1,'lingling','female');

unique 唯一

#单列唯一
create table test9 (
    id int unique,
    name char(16)
);
insert into test9 (id,name) values (1,'duomei');  #正常
insert into test9 values (1,'duoduo');  #报错
ERROR 1062 (23000): Duplicate entry '1' for key 'id'

#联合唯一
""
ip和port 单个都可以重复,但是加在一起必须是唯一的
""

create tebles test10 (
    id int,
    ip char(16),
    port int ,
    unique(ip,port)
);
insert into test10 values (1,'127.0.0.1',9090); #正常
insert into test10 values (2,'127.0.0.1',8090); #正常
insert into test10 values (3,'127.0.0.2',9090); #正常
insert into test10 values (4,'127.0.0.1',9090); #报错
ERROR 1062 (23000): Duplicate entry '127.0.0.1-8080' for key 'ip'

primary key 主键

"
1、单从约束效果上来看 primary key 等价于not null + unique  非空且唯一!!!
"

create table test11 (id int primary key,name char(16));
insert into test11 values (1,'duodian'); #正常
insert into test11 values (1,'duokan');  #报错
ERROR 1062 (23000): Duplicate entry '1' for key 'PRIMARY'

'
2、 它除了有约束效果之外 它还是innodb存储引擎组织数据的依据,innodb存储引擎在创建表的时候必须要有
primary key,因为它类似于书的目录,能够帮助提示查询效率并且也是建表的依据
'
# 1 一张表有且只有一个主键,如果你没有设置主键,那么会从上往下搜索直到遇到一个非空且唯一的字段
#将它自动升级为主键;

create table test12 (
    id int,
    name char(16),
    age int not null unique;
    addr char(32) not null unique;
    );
# 2 如果表中没有主键也没有其他任何非空且唯一字段,那么innodb会采用自己内部提供的一个隐藏字段作为主键
#隐藏意味着你无法使用到它,就无法提示查询速度;
# 3 一张表中都应有一个主键字段,并且通常将id字段作为主键;
#单个字段主键
create table test12 (id int primary key,name char(16));
#联合主键(多个字段联合起来作为表的主键,本质还是一个主键)
create table test13 (ip char(16),port int, primary key (ip,port));
# 也意味着,以后我们创建表的时候id字段一定要加primary key

auto_increment 自增

#当编号特别多的时候,人为的去维护太麻烦
create table test13 (id int primary key auto_increment,name char(16));
insert into test13 values (1,'jack'),('jay'),('jessy'),('rose');
# auto_increment 通常只能加在主键上的,不能给普通字段加

结论:

#以后在创建表的时候 id(数据的唯一标识 id 、uid、sid)字段的时候,id要创建主键并且是自增;
id int primary key auto_increment

原文地址:https://www.cnblogs.com/xiehong/p/14722067.html