【mySQL】 - 主键

什么是主键?

对于表中的每一行数据,都会有一个字段或一组字段,用于标识自己的唯一性,这样的一个或一组字段,就叫主键

如果没有这个主键,那么对于表中的每一行的管理,会陷入混乱,我要更新某一特定行的数值,该怎么选择呢?

主键需要满足什么条件?

a. 主键要满足唯一性:任何两行数据,其主键必定不相同。

b. 主键要满足非空性:主键如果为空,则无法起到标识此行的作用

c. 主键不做修改和更新

建表

CREATE TABLE person_test(
    id bigint not null,
    name varchar(20) not null default '王自健',
    sex varchar(10) 
);

创建带有主键的表

create table person_test(
    id      bigint      not null primary key,
    name    varchar(20) not null,
    sex     varchar(10) 
)

插入数据

insert into person_test(id, name, sex) values(01, '海涛', 'boy')

复合主键

复合主键就是一组字段标识一行

create table person_test(
    id      bigint      not null,
    name    varchar(20) not null,
    sex     varchar(10) ,
    primary key(id, name)
)

 

创建完后再决定主键 

create table person_test(
    id      bigint      not null ,
    name    varchar(20) not null,
    time    timestamp   default current_timestamp
);
alter table person_test add primary key (id);

 

 

 

posted @ 2018-07-13 00:19  NirvanaInFire  阅读(205)  评论(0编辑  收藏  举报