首页 > 数据库技术 > 详细

mysql 主键(primary)与null

时间:2021-05-13 13:57:18      阅读:28      评论:0      收藏:0      [点我收藏+]

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

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

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 abcd 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‘);

技术分享图片

 

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

 

null:空

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

eg:

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

desc test;

技术分享图片

 

mysql 主键(primary)与null

原文:https://www.cnblogs.com/yy51511/p/14763810.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!