1 Fork me on GitHub

29. SQL--主键:primary key

1. 前言

主键(primary key)由表中的一个或者多个字段构成,用来唯一标识表中的每一行记录。可以将主键类比为学号、身份证号、车牌号或者 id。

主键必须包含唯一值,换句话说,所有记录的主键都不能出现相同的值。此外,主键必须是一个具体的值,不能是 null 值。

当主键包含多个字段时,又称为复合键(composite primary key)。
注意事项
在设计主键时,应使用尽可能少的字段,这不但能减少存储空间,还能提升查询性能。主键包含的字段越少,所需要的存储空间就越小,就性能而言,更少的数据意味着更快速地处理。

sql 规定,主键长度不能超过 900 个字节。oracle 规定,主键不能超过 32 个字段。

2. 示例

下面的 SQL 语句将创建 website 表,并将 id 字段定义为主键:

create table website (
    id      int              not null   auto_increment,
    name    varchar(20)      not null,
    url     varchar(30),
    age     tinyint unsigned not null,
    alexa   int unsigned     not null,
    uv      float                       default '0',
    country char(3)          not null ,
    primary key (id)
);

最后一行将 id 字段定义为主键。

如果 website 表和 id 字段都已经存在,则可以使用 alter table 命令添加主键,语法如下:

alter table website add primary key (id);

注意,只有在首次创建数据表时,那些被声明为不能包含 null 值的字段,才能使用 alter table 命令添加为主键。
主键包含多个字段
在创建数据表时,为多个字段添加主键可以使用下面的 sql 语句:

create table website (
    id      int              not null   auto_increment,
    name    varchar(20)      not null,
    url     varchar(30),
    age     tinyint unsigned not null,
    alexa   int unsigned     not null,
    uv      float                       default '0',
    country char(3)          not null ,
    primary key (id, url)
);

最后一行将 id 和 url 字段设置为主键。

如果 website 表已经存在,则可以使用下面的 SQL 语句在 id 和 url 字段上添加主键:

alter table website
add constraint pk_custid primary key (id, url);

3. 删除主键

使用下面的语句可以删除表的主键约束:

alter table website drop primary key;

 

posted @ 2022-08-31 17:31  v_jjling  阅读(245)  评论(0编辑  收藏  举报
AmazingCounters.com