MySQL如何建立主鍵,外來鍵和復合主鍵

2021-10-25 10:28:03 字數 854 閱讀 2629

1.主鍵語法

①建立時:create table sc (

studentno    int,

courseid    int,

score    int,

primary key (studentno) );

②修改時:alter table table_name add constraint pk_name primary key(列名);

前提是原先沒有設定主鍵。

2.外來鍵語法

①建立時:create table sc (

studentno    int,

courseid    int,

score    int,

foreign key (courseid) );

②修改時:

alter table news_info[子表名]   add constraint fk_news_info_news_type[約束名] foreign key (info_id)[子表列] references news_type[主表名] (id)[主表列] ;

3.使用組合主鍵

如果一列不能唯一區分乙個表裡的記錄時,可以考慮多個列組合起來達到區分表記錄的唯一性,形式

①建立時:create table sc (

studentno    int,

courseid    int,

score    int,

primary key (studentno,courseid) );

②修改時:alter table tb_name add primary key (欄位1,欄位2,欄位3);

前提是原來表中沒有設定主鍵,若原先已有主鍵則會報錯。

MySQL如何建立主鍵,外來鍵和復合主鍵

1.主鍵語法 建立時 create table sc studentno int,courseid int,score int,primary key studentno 修改時 alter table table name add constraint pk name primary key 列名...

mysql主鍵和外來鍵

主鍵是本張表的主鍵,是唯一且非空的,而外鍵是另一張表中與這張表的某個欄位的型別,欄位名相同的字段,一般是用作關聯兩張或兩張以上的資料表時用的。以下面三張表為例 有三張表,一張表是讀者資訊,有乙個屬性為 readno 一張表是圖書的資訊,有乙個屬性是 bookno 一張表是借閱關係,有兩個屬性分別以讀...

MySQL 建立主鍵,外來鍵和復合主鍵的語句

1.建立主鍵語法 alter table table name add constraint pk name primary key 列名 2.建立外來鍵語法 alter table news info 子表名 add constraint fk news info news type 約束名 fo...