mysql主主外鍵建立:
(1)、確保參照的表和欄位是存在的
(2)、關聯表必須是Innodb儲存類型
(3)、必須設定主關聯表主鍵
(4)、主鍵與外鍵資料類型和字元編碼(unsigned)必須一致
(5)、確保以上聲明的句法是正確的
附:mysql建立表預設類型為:MYISAM
如果要改變預設表類型可在my.inf中加:default_storage_engine=INNODB
建立加外鍵表SQL語句樣本:
主表:
CREATE TABLE `building_info` (
`BuildingID` int(4) unsigned NOT NULL AUTO_INCREMENT,
`BuildingName` varchar(50) NOT NULL DEFAULT '',
`BuildingDesc` varchar(100) DEFAULT '',
PRIMARY KEY (`BuildingID`)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312;
外鍵表(關聯欄位:BuildingID):
CREATE TABLE `floor_info` (
`FloorID` int(4) unsigned NOT NULL AUTO_INCREMENT,
`BuildingID` int(4) unsigned NOT NULL DEFAULT '0',
`FloorName` varchar(50) NOT NULL DEFAULT '',
`FloorIndex` int(4) NOT NULL DEFAULT '0',
PRIMARY KEY (`FloorID`),
--KEY `Floor_Info_FK_BuildingID` (`BuildingID`),
constraint `Floor_Info_FK_BuildingID` foreign key (BuildingID) references BUILDING_INFO(BuildingID)
) ENGINE=InnoDB DEFAULT CHARSET=gb2312;
附:還可以建立好了表再建立索引:
例:
alter table FLOOR_INFO add constraint `Floor_Info_FK_ BuildingID` foreign key (FloorID) references BUILDING_INFO(FloorID);