![](/img/trans.png)
[英]Why I obtain this FK error when I try to create this table? errno: 150 "Foreign key constraint is incorrectly formed
[英]Why I obtain this error message when I try to set 2 foreign keys on a many to many association table? “Foreign key constraint is incorrectly formed”
我正在MySql上創建數據庫,但在嘗試設置與多對多關聯表相關的外鍵約束時遇到了一些困難。
所以基本上我有這兩個表:
1) 住宿 :每條記錄代表一家酒店,並具有以下字段:
Field Type Null Key Default Extra
---------------------------------------------------------------------------------------------------------------------------
id bigint(20) unsigned NO PRI auto_increment
user_id bigint(20) unsigned NO
accomodation_name varchar(100) NO
description text YES
nation varchar(100) YES
region varchar(100) YES
province varchar(100) YES
city varchar(100) YES
stars int(10) unsigned YES
geographical_position point YES
accomodation_typological_id bigint(20) unsigned YES MUL
accomodation_service_id bigint(20) YES
2) 服務 ,其中每條記錄代表上表的酒店提供的一項服務:
Field Type Null Key Default Extra
---------------------------------------------------------------------------------------------------------------------------
id bigint(20) NO PRI auto_increment
description varchar(255) NO
好的,然后我有一個名為accomodation_service的關聯表,該表實現了前兩個表之間的多對多關系,這是其結構:
Field Type Null Key Default Extra
---------------------------------------------------------------------------------------------------------------------------
id bigint(20) unsigned NO PRI auto_increment
accomodation_id bigint(20) unsigned NO MUL
service_id bigint(20) unsigned NO
因此,如您所見,此accomodation_service表將住宿表的記錄與服務表的記錄相關聯。
我的問題是嘗試在此表中設置外鍵 。
具體而言, accomodation_id必須僅包含住宿表的id值,而service_id必須僅包含服務表的id值。
因此,我嘗試使用Database WorkBanch 5 (我的IDE)提供的圖形工具來做到這一點:
但是我發現了一些困難,因為當我嘗試執行此約束設置時,IDE會顯示以下錯誤消息:
#HY000Can't create table `testdb`.`#sql-417c_4b` (errno: 150 "Foreign key constraint is incorrectly formed")
while executing:
ALTER TABLE accomodation_service ADD CONSTRAINT fk_accomodation_service_service FOREIGN KEY (service_id)
REFERENCES service (id)
ON DELETE NO ACTION
ON UPDATE NO ACTION
為什么? 是IDE問題還是我缺少什么? 我該怎么做才能解決這個問題? 我要執行什么查詢才能正確設置這兩個前鍵?
accomodation_service關聯表不需要您定義的新主鍵“ ID”。 您需要從accomodation_service表中刪除ID屬性,並將“ accomodation_id”和“ service_id”設置為組合主鍵。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.