主鍵(primary key)和唯一鍵(unique) 知識點總結(jié)

Primary key

  • 概念
    主鍵用于唯一標(biāo)識表中的每一條數(shù)據(jù)

  • 主鍵的特征:
    不能重復(fù), 不能為空

示例

create table if not exists stu(
    id int auto_increment primary key, <------#主建
    name varchar(20)
);
注意點:

auto_increment的字段必須是主鍵, 但是主鍵不一定是auto_increment的, 只要是唯一的就可以 一個表只能有一個主鍵, 但是主鍵可以是1個或多個字段組成

auto_increment 自增長
1. 自增長字段的值從1開始, 每次遞增1
2. 自增長字段數(shù)據(jù)不可以重復(fù), 合適生成唯一的id
3. 自增長字段可以使用null或者default來設(shè)置值
4. 自增長字段必須是主鍵 (primary key)

示例演示

示例1

# 錯誤示例

create table if not exists stu2(
    id int auto_increment, <------#會報錯, 自增長的字段必須是主鍵
    name varchar(20)
);

示例2

create table if not exists stu2(
    id int primary key, <------#不會報錯, 主鍵不一定是自增長的
    name varchar(20)
);

#如果主鍵不是自增長的, 那么不能為空 

#主鍵不能重復(fù)

示例3

# 錯誤示例

create table if not exists stu3(
    id1 int primary key,
    id2 int primary key, <------#一張表只能有一個主鍵
    name varchar(20)
);

#正確的寫法

create table if not exists stu3(
    id1 int primary key,
    id2 int,
    name varchar(20)
);

示例4

#指定主鍵的第二種格式

create table if not exists stu4(
    id1 int,
    id2 int,
    name varchar(20),
    primary key(id1) 
);

示例5

create table if not exists stu6(
    id int,
    name varchar(20)
);

# 沒有主鍵的情況下添加主建
alter table stu6 add primary key(id);


示例6

# 聯(lián)合主建
create table if not exists stu5(
    id1 int,
    id2 int,
    name varchar(20),
    primary key(id1,id2)
);

#不是指定兩個主鍵, 一個primary key就是指定一個主鍵
#這里只出現(xiàn)了一個primary key, 所以只指定了一個主鍵
#只不過這個主鍵比較特殊, 是由兩個字段共同組成的
聯(lián)合主鍵的應(yīng)用場景:
  1. 如下一張表無論哪一個字段都無法保證數(shù)據(jù)的唯一性,
  2. 所以可以使用多個字段組合再一起保證數(shù)據(jù)的唯一性
企業(yè)開發(fā)中如何選擇主鍵?
  1. 最少性: 盡量選擇一個字段作為主鍵
  2. 穩(wěn)定性: 盡量選擇更新少的字段作為主鍵
  3. 盡量選擇整數(shù)類型的字段作為主鍵
  4. 結(jié)論: 搞一個id字段類型為int, 設(shè)置自動增長, 作為主鍵

唯一鍵unique

作用

避免添加重復(fù)數(shù)據(jù), 也就是說如果想保證某一個字段的值永遠(yuǎn)不重復(fù), 那么就可以將這個字段設(shè)置為唯一鍵

注意點:
  • 唯一鍵不是主鍵, 主鍵有一個特點是不能重復(fù), 但是唯一鍵不等于主鍵
  • 一張表中只能有一個主鍵, 但是一張表中可以有多個唯一鍵
示例1

create table if not exists stu1(
    id int auto_increment primary key,
    name varchar(20) <------ #可以添加重復(fù)數(shù)據(jù)
);


create table if not exists stu2(
    id int auto_increment primary key,
    name varchar(20) unique <------#不可以添加重復(fù)數(shù)據(jù)
);

#添加唯一鍵的第二種方式

create table if not exists stu(
    id int auto_increment primary key,
    name varchar(20),
    unique key(name) <------#給name添加唯一鍵 name不可以添加重復(fù)數(shù)據(jù)
);


示例3

create table if not exists stu(
    id int auto_increment primary key,
    name varchar(20)
);

alter table stu add unique(name); <------#指定唯一鍵

示例4
# 指定多個唯一鍵

create table if not exists stu11(
    id int auto_increment primary key,
    name varchar(20) unique,
    score int unique
);
刪除唯一鍵
格式
alter table 表名 drop index  唯一鍵字段名;

示例
alter table stu11 drop index name;  
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容