MySql創建多表關聯的步驟


一,一對多表的創建

1.創建主表

create table HostTable(
  cid varchar(32) primary key,
  cname varchar(100)
);

2.創建從表

create table FromTable(
  pid varchar(32) primary key,
  pname varchar(40),
  price double,
);

3.給從表創建從鍵列

alter table FromTable add hosttable_id varchar(32);

4.添加約束

alter table FromTable  add constraint fromtable _fk foreign key(hosttable_id ) references HostTable(cid);

 

二,多對多表的創建

引入一張中間表,存儲兩個從鍵分別引用於兩個主鍵。兩個從鍵可以多次重復。這樣就實現了多對多的表關系。

create table  InterTable(

  hosttableid  varchar(32),

  fromtableid  varchar(32) 

);

1.添加聯合主鍵

alter table InterTable add primary key (hosttableid, fromtableid );

2.添加約束

alter table InterTable add constraint   inter_hosttable_fk foreign key (hosttableid) referrences HostTable(cid);

alter table InterTable add constraint   inter_fromtable_fk foreign key (fromtableid) referrences FromTable(pid );

這時InterTable 和 HostTable ,FromTable分別都是一對多的

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM