2015-05-21 154 views
1

我患有與其他人在此處相同的「無法添加外鍵約束」。錯誤「無法添加外鍵約束」

client_partners包含用戶之間的關係。創建client_partners時會引發錯誤。

我已經檢查了users.id具有相同類型的比client_partners.clientidclient_partners.partneridINT UNSIGNED NOT NULL

配置選項包括:

SET @[email protected]@UNIQUE_CHECKS, UNIQUE_CHECKS=0; 
SET @[email protected]@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; 
SET @[email protected]@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES'; 

用戶表定義:

-- ----------------------------------------------------- 
-- Table `users` 
-- ----------------------------------------------------- 
DROP TABLE IF EXISTS `users` ; 

CREATE TABLE IF NOT EXISTS `users` (
    `id` INT UNSIGNED NOT NULL AUTO_INCREMENT, 
    `username` VARCHAR(50) NOT NULL, 
    `password` VARCHAR(200) NOT NULL, 
    `salt` VARCHAR(100) NULL, 
    `firstname` VARCHAR(50) NOT NULL, 
    `lastname` VARCHAR(50) NOT NULL, 
    `email` VARCHAR(50) NOT NULL, 
    `role` VARCHAR(10) NOT NULL DEFAULT 'supplier', 
    `destination` VARCHAR(10) NULL, 
    `supplierId` INT UNSIGNED NULL, 
    `created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, 
    `updated` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, 
    PRIMARY KEY (`id`), 
    UNIQUE INDEX `username_UNIQUE` (`username` ASC), 
    INDEX `fk_users_suppliers_idx` (`supplierId` ASC), 
    INDEX `fk_users_roles_idx` (`role` ASC), 
    INDEX `fk_users_destinations1_idx` (`destination` ASC), 
    CONSTRAINT `fk_users_suppliers` 
    FOREIGN KEY (`supplierId`) 
    REFERENCES `suppliers` (`id`) 
    ON DELETE NO ACTION 
    ON UPDATE NO ACTION, 
    CONSTRAINT `fk_users_roles` 
    FOREIGN KEY (`role`) 
    REFERENCES `roles` (`id`) 
    ON DELETE NO ACTION 
    ON UPDATE NO ACTION, 
    CONSTRAINT `fk_users_destinations1` 
    FOREIGN KEY (`destination`) 
    REFERENCES `destinations` (`id`) 
    ON DELETE NO ACTION 
    ON UPDATE NO ACTION) 
ENGINE = InnoDB 

Client_partners表定義:

-- ----------------------------------------------------- 
-- Table `client_partners` 
-- ----------------------------------------------------- 
DROP TABLE IF EXISTS `client_partners` ; 

CREATE TABLE IF NOT EXISTS `client_partners` (
    `clientid` INT UNSIGNED NOT NULL, 
    `partnerid` INT UNSIGNED NOT NULL, 
    PRIMARY KEY (`clientid`, `partnerid`), 
    CONSTRAINT `fk_client_partners_1` 
    FOREIGN KEY (`clientid` , `partnerid`) 
    REFERENCES `users` (`id` , `id`) 
    ON DELETE NO ACTION 
    ON UPDATE NO ACTION) 
ENGINE = InnoDB; 

的數據類型(除了自動增量)是相同的。引用表(用戶)首先被創建。我錯過了什麼?

+0

它仍然不清楚你的問題;哪個表失敗? – Mihai

+0

創建表client_partners時引發錯誤。感謝您指出它,我也編輯了這個問題。 –

+1

你不能在一個複合外鍵中有相同的列,也許你想要每個列有兩個外鍵'CONSTRAINT'fk_client_partners_1' FOREIGN KEY('clientid') REFERENCES'users'('id')'same for partnerid just更改約束名稱 – Mihai

回答

1
CONSTRAINT `fk_client_partners_1`  
FOREIGN KEY (`clientid` , `partnerid`) 
REFERENCES `users` (`id` , `id`) 

這裏你引用表的idusers twice..it是不可能的。嘗試刪除一個並創建

如果要引用另一個外鍵,則需要使用其他名稱創建它。

+0

謝謝,薩楚。正如Mihai所說,這不是做這件事的方法:我必須爲第二個關鍵點創建另一個約束。 –