mysql 主键(primary)与null


主键(建表时设置主键方式1):
constraint unique(id):id那一列为主键,任何一个id都不能相同
constraint unique(id,lastname):id和lastname两列为主键,两列都相同则不能插入,只有一列相同或者两列都不相同则可以插入
constraint unique(id)在create table时填写,放在最后

constraint:(约束,限定)
unique:(唯一的,独特的)

pri=primary(主要的)

constraints 限制加入表的数据类型

eg1:创建主键为id的test表

create table test (id int not null, lastname varchar(255) not null,firstname varchar(255),address varchar(255),city varchar(255),constraint unique(id));

desc test;

 

 诠释:desc table之后列名称key代表主键,里边写的pri则代表一个列为主键,pri=primary(主要的)

然后输入两个相同的主键

insert into test (id,lastname,firstname) values(1,'adams','john');

insert into test (id,lastname,firstname) values(1,'adams','john');

 

  诠释:id为主键,所以1只能出现一次

eg2:创建两个主键

创建id,lastname为主键

create table test (id int not null, lastname varchar(255) not null,firstname varchar(255),address varchar(255),city varchar(255),constraint  unique(id,lastname));

desc test;

插入:两个主键完全相同的内容(第二次插入不成功)

insert into test (id,lastname,firstname) values(1,'adams','john');

insert into test (id,lastname,firstname) values(1,'adams','john');

 

   诠释:两列都相同则不能插入(只有一列相同或者两列都不相同则可以插入

建表时设置主键方式2:

方式2与方式1的区别:

 

1、创建表时两个方式的区别 primary key:比如id是主键,id不能为空   unique:主键可以为空

unique:撤销唯一性

2、对应primary key(id)); constraint abcd primary key(id,lastname));

------alter table test drop primary key;只用这个撤销

------想设置多个主键就要用constraint abcd primary key(id,lastname)); primary key(id));只能添加一个

3、alter table test add constraint abcd unique(id);用

------create table test (id int not null, lastname varchar(255) not null,firstname varchar(255),address varchar(255),city varchar(255),constraint abcd unique(id,lastname));

对应alter table test drop index abcd;(区别是有index)

 

建表后再设置主键:

设置一个主键:alter table test(表) add constraint abcd unique(id);

设置多个主键:alter table test add constraint abcd unique(id,lastname);

撤销主键:

alter table test

 

null:空

not null:非空,但如果写到create table里边,则为空值不能写null的意思
建表时没有写not null:查询表时,空值默认显示null
建表时对应数字的数字的列写了not null,例如id,查询时空值显示:0
建表时对应字节的列写了not null,查询表时,空值显示为空,什么都没有
default:desc table时,default的意思为:默认

eg:创建id,lastname,空值不为null的test表

create table test (id int not null, lastname varchar(255) not null,firstname varchar(255),address varchar(255),city varchar(255));

desc test;

 

  诠释:id对应的数字显示为0,lastname对应的字段显示为空

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM