MySQL添加/刪除主鍵、外鍵、唯一鍵、索引、自增

原文鏈接:https://blog.csdn.net/u011712163/article/details/78560881

版權聲明:本文爲博主原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接和本聲明。
本文鏈接:https://blog.csdn.net/u012643122/article/details/52890772
主鍵

主鍵會自動添加唯一索引,所以主鍵列不需要添加索引
建表時設置主鍵

create table tableName(
    id int primary key
);
或:
create table tableName(
    id int,
    primary key (id)
);

    1
    2
    3
    4
    5
    6
    7
    8

單獨設置主鍵

alter table tableName add primary key(id)

    1

刪除主鍵

alter table tableName drop primary key;

    1

外鍵
建表時添加外鍵

create table tableName1(
    tableName2_id int not null,
    foreign key(tableName2_id) references tableName2(id)
);

    1
    2
    3
    4

單獨添加外鍵

alter table tableName1 add constraint tableName1_ref_tableName2(foreignKeyName) foreign key(tableName2_id) references tableName2(id);

    1

刪除外鍵

alter table table1 drop foreign key foreignKeyName;

    1

唯一鍵

唯一鍵會自動添加唯一索引,所以唯一鍵列不需要添加索引
建表時添加唯一鍵

create table tableName(
    columnName int unique
);
或:
create table tableName(
    columnName int,
    unique key(columnName)
);

    1
    2
    3
    4
    5
    6
    7
    8

單獨添加唯一鍵

alter table tableName add unique key(columnName)

    1

刪除唯一鍵

alter table tableName drop index columnName;

    1

索引

很多情況,mysql中的索引index和鍵key是同義詞。
fulltext全文索引,只有MyISAM引擎支持,就不說了。
建表時添加索引

create table tableName(
    columnName int key//這裏只能用key不能用index
);
或:
create table tableName(
    columnName int,
    key/index (columnName)
);
或:
create table tableName(
    columnName int,
    key/index indexName(columnName)
);
多列索引:
create table tableName(
    columnName1 int,
    columnName2 int,
    key/index indexName(columnName1,columnName2)
);

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19

單獨添加索引

alter table tableName add key/index indexName(columnName)//單列索引
alter table tableName add key/index indexName(columnName1,columnName2,columnName3)//多列索引

    1
    2

刪除索引

alter table tableName drop key/index columnName;

    1

自增

auto_increment必須要求該列是主鍵(或別的鍵,詳細請看文章:http://blog.csdn.net/u012643122/article/details/52643888)
建表時添加自增

create table tableName(
    columnName int unique auto_increment
);
或:
create table tableName(
    columnName int primary key auto_increment
);

    1
    2
    3
    4
    5
    6
    7

單獨添加自增

alter table tableName change columnName columnName int unique auto_increment;
或:
alter table tableName change columnName columnName int primary key auto_increment;

    1
    2
    3

刪除自增

alter table tableName change columnName columnName int;

    1

設置自增初始值

create table tableName(
    columnName int primary key auto_increment
)auto_increment=1;
或:
alter table tableName auto_increment=1;
————————————————
版權聲明:本文爲CSDN博主「思想永無止境」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/u012643122/article/details/52890772

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章