我患有與其他人在此處相同的「無法添加外鍵約束」。錯誤「無法添加外鍵約束」
表client_partners包含用戶之間的關係。創建client_partners時會引發錯誤。
我已經檢查了users.id具有相同類型的比client_partners.clientid和client_partners.partnerid:INT 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;
的數據類型(除了自動增量)是相同的。引用表(用戶)首先被創建。我錯過了什麼?
它仍然不清楚你的問題;哪個表失敗? – Mihai
創建表client_partners時引發錯誤。感謝您指出它,我也編輯了這個問題。 –
你不能在一個複合外鍵中有相同的列,也許你想要每個列有兩個外鍵'CONSTRAINT'fk_client_partners_1' FOREIGN KEY('clientid') REFERENCES'users'('id')'same for partnerid just更改約束名稱 – Mihai