MySQL聯合主鍵,複合主鍵區別&建立
阿新 • • 發佈:2019-01-25
聯合主鍵:
當兩個資料表形成的是多對多的關係,那麼需要通過兩個資料表的主鍵來組成聯合主鍵,就可以確定每個資料表的其中一條記錄了
例:
學生表:student
create table student(
id mediumint auto_increment comment '主鍵id',
name varchar(30) comment '姓名',
age smallint comment '年齡',
primary key(id)
)
engine = myisam,
charset = utf8,
comment = '學生'
課程表:course
create table course( id mediumint auto_increment comment '主鍵id', name varchar(30) comment '課程名稱', primary key(id) ) engine = myisam, charset = utf8, comment = '課程'
學生課程表:stu_cour
create table IF NOT EXISTS stu_cour(
id mediumint auto_increment comment '主鍵id',
stu_id mediumint comment '學生表id',
cour_id mediumint comment '課程表id',
primary key(id)
)
engine = myisam,
charset = utf8,
comment = '學生課程表'
此時,就可以通過學生課程表的id來獲取對應的學生表和課程表的一條記錄資訊,此時,學生課程表的id就是聯合主鍵的結果
複合主鍵:
在一個數據表中通過多個欄位作為主鍵來確定一條記錄,那麼,多個欄位組成的就是複合主鍵
create table student(
name varchar(30) comment '姓名',
age smallint comment '年齡',
sex enum('男','女') comment '性別',
primary key(name,age)
)
engine = myisam,
charset = utf8,
comment = '學生'
聯合主鍵修改:
資料庫操作中有時需要將一個主鍵修改為聯合主鍵或者把主鍵改為其他列,這時候單純的add primary key是沒有用的,必須先刪除主鍵約束,再重新新增。
alter table TABNAME drop primary key;
alter table TABNAME add primary key(another_col,...);
復合主鍵修改:
alter table 表名 add primary key (欄位1,欄位2,欄位3);
如果執行上面操作提示表不能有多個主鍵錯誤時,需要先清理主鍵約束
,再執行新增。
alter table 表名 DROP PRIMARY KEY add primary key (欄位1,欄位2,欄位3);