I made a diagram (EER) in MySQL-Workbench and trying to do "Forward Engineer to DataBase" gave me this error "Error 1215: Cannot add foreign key constraint" and can't identify the error in the code.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Code:
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Schema loja1182
CREATE SCHEMA IF NOT EXISTS `loja1182` DEFAULT CHARACTER SET utf8 COLLATE utf8_bin ;
USE `loja1182` ;
Table loja1182.distritos
CREATE TABLE IF NOT EXISTS `loja1182`.`distritos` (
`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`distrito` VARCHAR(50) NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
Table loja1182.clientes
CREATE TABLE IF NOT EXISTS `loja1182`.`clientes` (
`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`nome` VARCHAR(100) NULL,
`morada` VARCHAR(100) NULL,
`data_registo` DATE NOT NULL,
`nrEncomendas` INT(11) NULL,
`idDistrito` INT(11) UNSIGNED NOT NULL,
PRIMARY KEY (`id`),
INDEX `fk_clientes_table11_idx` (`idDistrito` ASC),
CONSTRAINT `fk_clientes_table11`
FOREIGN KEY (`idDistrito`)
REFERENCES `loja1182`.`distritos` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
Table loja1182.utilizadores
CREATE TABLE IF NOT EXISTS `loja1182`.`utilizadores` (
`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`email` VARCHAR(100) NULL,
`password` VARCHAR(20) NULL,
`total_acessos` INT NULL,
`idCliente` INT(11) UNSIGNED NOT NULL,
PRIMARY KEY (`id`),
INDEX `fk_utilizadores_clientes_idx` (`idCliente` ASC),
CONSTRAINT `fk_utilizadores_clientes`
FOREIGN KEY (`idCliente`)
REFERENCES `loja1182`.`clientes` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
Table loja1182.tiposencomenda
CREATE TABLE IF NOT EXISTS `loja1182`.`tiposencomenda` (
`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`tipo` VARCHAR(20) NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
Table loja1182.estadosencomenda
CREATE TABLE IF NOT EXISTS `loja1182`.`estadosencomenda` (
`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`estado` VARCHAR(20) NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
Table loja1182.encomendas
CREATE TABLE IF NOT EXISTS `loja1182`.`encomendas` (
`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`idCliente` INT(11) UNSIGNED NOT NULL,
`data` DATE NULL,
`idEstado` INT(11) UNSIGNED NOT NULL,
`idTipo` INT(11) UNSIGNED NOT NULL,
`valor` FLOAT NULL,
PRIMARY KEY (`id`),
INDEX `fk_encomendas_clientes1_idx` (`idCliente` ASC),
INDEX `fk_encomendas_tiposencomenda1_idx` (`idTipo` ASC),
INDEX `fk_encomendas_estadosencomenda1_idx` (`idEstado` ASC),
CONSTRAINT `fk_encomendas_clientes1`
FOREIGN KEY (`idCliente`)
REFERENCES `loja1182`.`clientes` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_encomendas_tiposencomenda1`
FOREIGN KEY (`idTipo`)
REFERENCES `loja1182`.`tiposencomenda` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_encomendas_estadosencomenda1`
FOREIGN KEY (`idEstado`)
REFERENCES `loja1182`.`estadosencomenda` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
Table loja1182.categorias
CREATE TABLE IF NOT EXISTS `loja1182`.`categorias` (
`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`categoria` VARCHAR(50) NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
Table loja1182.iva
CREATE TABLE IF NOT EXISTS `loja1182`.`iva` (
`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`taxa` FLOAT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
Table loja1182.artigos
CREATE TABLE IF NOT EXISTS `loja1182`.`artigos` (
`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`descricao` VARCHAR(100) NULL,
`precos` FLOAT NULL,
`idIva` INT(11) UNSIGNED NOT NULL,
`stock` INT(11) NOT NULL,
`idCategoria` INT(11) UNSIGNED NOT NULL,
PRIMARY KEY (`id`),
INDEX `fk_artigos_categorias1_idx` (`idCategoria` ASC),
INDEX `fk_artigos_iva1_idx` (`idIva` ASC),
CONSTRAINT `fk_artigos_categorias1`
FOREIGN KEY (`idCategoria`)
REFERENCES `loja1182`.`categorias` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_artigos_iva1`
FOREIGN KEY (`idIva`)
REFERENCES `loja1182`.`iva` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
Table loja1182.linhasencomenda
CREATE TABLE IF NOT EXISTS `loja1182`.`linhasencomenda` (
`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`idEncomenda` INT(11) UNSIGNED NOT NULL,
`idArtigo` INT(11) UNSIGNED NOT NULL,
`quantidade` INT(11) NOT NULL,
PRIMARY KEY (`id`),
INDEX `fk_linhasencomenda_encomendas1_idx` (`idEncomenda` ASC),
INDEX `fk_linhasencomenda_artigos1_idx` (`idArtigo` ASC),
CONSTRAINT `fk_linhasencomenda_encomendas1`
FOREIGN KEY (`idEncomenda`)
REFERENCES `loja1182`.`encomendas` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_linhasencomenda_artigos1`
FOREIGN KEY (`idArtigo`)
REFERENCES `loja1182`.`artigos` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
ERROR:
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Executing SQL script in server
ERROR: Error 1215: Cannot add foreign key constraint
SQL Code:
Table `loja1182`.`encomendas`
CREATE TABLE IF NOT EXISTS `loja1182`.`encomendas` (
`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`idCliente` INT(11) UNSIGNED NOT NULL,
`data` DATE NULL,
`idEstado` INT(11) UNSIGNED NOT NULL,
`idTipo` INT(11) UNSIGNED NOT NULL,
`valor` FLOAT NULL,
PRIMARY KEY (`id`),
INDEX `fk_encomendas_clientes1_idx` (`idCliente` ASC),
INDEX `fk_encomendas_tiposencomenda1_idx` (`idTipo` ASC),
INDEX `fk_encomendas_estadosencomenda1_idx` (`idEstado` ASC),
CONSTRAINT `fk_encomendas_clientes1`
FOREIGN KEY (`idCliente`)
REFERENCES `loja1182`.`clientes` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_encomendas_tiposencomenda1`
FOREIGN KEY (`idTipo`)
REFERENCES `loja1182`.`tiposencomenda` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_encomendas_estadosencomenda1`
FOREIGN KEY (`idEstado`)
REFERENCES `loja1182`.`estadosencomenda` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
SQL script execution finished: statements: 10 succeeded, 1 failed
Fetching back view definitions in final form.
Nothing to fetch
I had created those tables:
CREATE TABLE `course` (
`idcourse` varchar(2) NOT NULL,
`courseName` varchar(45) NOT NULL,
`subjectID` varchar(2) NOT NULL,
PRIMARY KEY (`idcourse`),
KEY `subjectID_idx` (`subjectID`),
CONSTRAINT `subjectID` FOREIGN KEY (`subjectID`) REFERENCES `subject` (`idsubject`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1
CREATE TABLE `exam` (
`subjectID` varchar(2) NOT NULL,
`courseID` varchar(2) NOT NULL,
`examNumber` varchar(2) NOT NULL,
`duration` int(11) DEFAULT NULL,
PRIMARY KEY (`subjectID`,`courseID`,`examNumber`),
KEY `idCourse_idx` (`courseID`),
CONSTRAINT `idCo` FOREIGN KEY (`courseID`) REFERENCES `course` (`idcourse`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `idSu` FOREIGN KEY (`subjectID`) REFERENCES `subject` (`idsubject`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1
CREATE TABLE `question` (
`questionText` varchar(100) DEFAULT NULL,
`answer1` varchar(100) DEFAULT NULL,
`answer2` varchar(100) DEFAULT NULL,
`answer3` varchar(100) DEFAULT NULL,
`answer4` varchar(100) DEFAULT NULL,
`subjetID` varchar(2) NOT NULL,
`questionNumber` varchar(3) NOT NULL,
`rightAnswer` int(4) DEFAULT NULL,
PRIMARY KEY (`subjetID`,`questionNumber`),
CONSTRAINT `idsubject` FOREIGN KEY (`subjetID`) REFERENCES `subject` (`idsubject`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1
CREATE TABLE `subject` (
`idsubject` varchar(2) NOT NULL,
`subjectName` varchar(45) NOT NULL,
PRIMARY KEY (`idsubject`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
To subject table I add a record:
idsubject = 02, subjectName = Mathematica
To course table I add a record:
idcourse = 03, courseName = Algebra 1, subjectID = 02
To exam table I add a record:
subjectID = 02, courseID = 03, examNumber = 01, duration = 180
Now, I want to create a table: questionsinexam
CREATE TABLE `test`.`questionsinexam` (
`idExamSubject` VARCHAR(2) NOT NULL,
`idExamCourse` VARCHAR(2) NOT NULL,
`idExamNumber` VARCHAR(2) NOT NULL,
`idQuestionNumber` VARCHAR(3) NOT NULL,
`pointsPerQuestion` INT NULL,
PRIMARY KEY (`idExamSubject`, `idExamCourse`, `idExamNumber`, `idQuestionNumber`),
INDEX `idExamCourse_idx` (`idExamCourse` ASC),
INDEX `idExamNumber_idx` (`idExamNumber` ASC),
INDEX `idQuestionNumber_idx` (`idQuestionNumber` ASC),
CONSTRAINT `idExamSubject`
FOREIGN KEY (`idExamSubject`)
REFERENCES `test`.`exam` (`subjectID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `idExamCourse`
FOREIGN KEY (`idExamCourse`)
REFERENCES `test`.`exam` (`courseID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `idExamNumber`
FOREIGN KEY (`idExamNumber`)
REFERENCES `test`.`exam` (`examNumber`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `idQuestionNumber`
FOREIGN KEY (`idQuestionNumber`)
REFERENCES `test`.`question` (`questionNumber`)
ON DELETE NO ACTION
ON UPDATE NO ACTION);
Why I'm getting this error?
Thanks.
This constraint is definitely wrong:
CONSTRAINT `idExamSubject`
FOREIGN KEY (`idExamSubject`)
REFERENCES `test`.`exam` (`subjectID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
Perhaps you intend:
CONSTRAINT `idExamSubject`
FOREIGN KEY (`idExamSubject`)
REFERENCES `test`.`subject` (`subjectID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
Be sure that you create the target tables before you create the foreign key constraint. The referred to table needs to exist first (so the engine can validate types on the columns used for the foreign key).
MySQL Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'fkUsers6' in the reference table 'users'
Happens when there is more than one foreign key of the same type in the table. Any idea to solve this? I haven't found answers to this case yet ...
Table in which the error occurs:
CREATE TABLE IF NOT EXISTS `profiCRM`.`opportunities` (
`ID` INT NOT NULL AUTO_INCREMENT,
`opportunity_belongsTo` INT NULL,
`opportunity_description` VARCHAR(45) NOT NULL,
`opportunity_type` INT NOT NULL,
`opportunity_stage` INT NOT NULL,
`opportunity_product` INT NOT NULL,
`opportunity_volume` INT NOT NULL,
`opportunity_dateCreated` DATETIME NOT NULL,
`opportunity_createdFrom` INT NOT NULL,
`opportunity_datePlannedClosure` DATE NOT NULL,
`opportunity_dateChanged` DATETIME NULL,
`opportunity_changedFrom` INT NULL,
`opportunity_dateClosed` DATETIME NULL,
`opportunity_closedFrom` INT NULL,
`opportunity_dateDeleted` DATETIME NULL,
`opportunity_deletedFrom` INT NULL,
PRIMARY KEY (`ID`));
Creation of the foreign keys:
ALTER TABLE `profiCRM`.`opportunities`
ADD INDEX `fkAccounts_idx` (`opportunity_belongsTo` ASC),
ADD INDEX `fkOpportunityStage_idx` (`opportunity_stage` ASC),
ADD INDEX `fkOpportunityType_idx` (`opportunity_type` ASC),
ADD INDEX `fkProducts_idx` (`opportunity_product` ASC),
ADD INDEX `fkUsers_idx` (`opportunity_createdFrom` ASC, `opportunity_changedFrom` ASC, `opportunity_closedFrom` ASC, `opportunity_deletedFrom` ASC),
ADD CONSTRAINT `fkAccounts6`
FOREIGN KEY (`opportunity_belongsTo`)
REFERENCES `profiCRM`.`accounts` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
ADD CONSTRAINT `fkOpportunityStage6`
FOREIGN KEY (`opportunity_stage`)
REFERENCES `profiCRM`.`opportunityStage` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
ADD CONSTRAINT `fkOpportunityType6`
FOREIGN KEY (`opportunity_type`)
REFERENCES `profiCRM`.`opportunityTypes` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
ADD CONSTRAINT `fkProducts6`
FOREIGN KEY (`opportunity_product`)
REFERENCES `profiCRM`.`products` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
ADD CONSTRAINT `fkUsers6`
FOREIGN KEY (`opportunity_createdFrom` , `opportunity_changedFrom` , `opportunity_closedFrom` , `opportunity_deletedFrom`)
REFERENCES `profiCRM`.`users` (`ID` , `ID` , `ID` , `ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
Table of which the foreign key is from:
CREATE TABLE IF NOT EXISTS `profiCRM`.`users` (
`ID` INT NOT NULL AUTO_INCREMENT,
`user_belongsTo` INT NOT NULL,
`user_firstName` VARCHAR(45) NOT NULL,
`user_lastName` VARCHAR(45) NOT NULL,
`user_dateOfBirth` DATE NOT NULL,
`user_adress1` VARCHAR(45) NOT NULL,
`user_adress2` VARCHAR(45) NULL,
`user_department` VARCHAR(45) NOT NULL,
`user_zipcode` VARCHAR(10) NOT NULL,
`user_city` VARCHAR(45) NOT NULL,
`user_state` VARCHAR(45) NULL,
`user_country` INT NOT NULL,
`user_email` VARCHAR(45) NOT NULL,
`user_telephoneFixed` VARCHAR(45) NULL,
`user_telephoneMobile` VARCHAR(45) NULL,
`user_rightViewData` INT NOT NULL,
`user_rightCreateData` TINYINT NULL,
`user_rightCreateUser` TINYINT NULL,
`user_rightCreateAttribute` TINYINT NULL,
`user_rightCreateList` TINYINT NULL,
`user_rightEditData` TINYINT NULL,
`user_rightEditUser` TINYINT NULL,
`user_rightEditAttribute` TINYINT NULL,
`user_rightEditList` TINYINT NULL,
`user_rightDeleteData` TINYINT NULL,
`user_rightDeleteUser` TINYINT NULL,
`user_rightDeleteAttribute` TINYINT NULL,
`user_rightDeleteList` TINYINT NULL,
`user_dateCreated` DATETIME NOT NULL,
`user_createdFrom` INT NULL,
`user_dateChanged` DATETIME NULL,
`user_changedFrom` INT NULL,
`user_dateDeleted` DATETIME NULL,
`user_deletedFrom` INT NULL,
PRIMARY KEY (`ID`));
Here the solution: (I had to define an own foreign key for every
single list item, the possibility to select several items for one key
in the MySQL Workbench is not such purposeful)
-- MySQL Script generated by MySQL Workbench
-- Wed Oct 25 14:20:25 2017
-- Model: New Model Version: 1.0
-- MySQL Workbench Forward Engineering
SET #OLD_UNIQUE_CHECKS=##UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET #OLD_FOREIGN_KEY_CHECKS=##FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET #OLD_SQL_MODE=##SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Schema profiCRM
-- -----------------------------------------------------
-- -----------------------------------------------------
-- Schema profiCRM
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `profiCRM` DEFAULT CHARACTER SET utf8 ;
SHOW WARNINGS;
USE `profiCRM` ;
-- -----------------------------------------------------
-- Table `profiCRM`.`countries`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `profiCRM`.`countries` (
`ID` INT NOT NULL AUTO_INCREMENT,
`countryName` VARCHAR(45) NULL,
PRIMARY KEY (`ID`),
UNIQUE INDEX `ID_UNIQUE` (`ID` ASC))
ENGINE = InnoDB;
SHOW WARNINGS;
-- -----------------------------------------------------
-- Table `profiCRM`.`users`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `profiCRM`.`users` (
`ID` INT NOT NULL AUTO_INCREMENT,
`user_belongsTo` INT NOT NULL,
`user_firstName` VARCHAR(45) NOT NULL,
`user_lastName` VARCHAR(45) NOT NULL,
`user_dateOfBirth` DATE NOT NULL,
`user_adress1` VARCHAR(45) NOT NULL,
`user_adress2` VARCHAR(45) NULL,
`user_department` VARCHAR(45) NOT NULL,
`user_zipcode` VARCHAR(10) NOT NULL,
`user_city` VARCHAR(45) NOT NULL,
`user_state` VARCHAR(45) NULL,
`user_country` INT NOT NULL,
`user_email` VARCHAR(45) NOT NULL,
`user_telephoneFixed` VARCHAR(45) NULL,
`user_telephoneMobile` VARCHAR(45) NULL,
`user_rightViewData` INT NOT NULL,
`user_rightCreateData` TINYINT NULL,
`user_rightCreateUser` TINYINT NULL,
`user_rightCreateAttribute` TINYINT NULL,
`user_rightCreateList` TINYINT NULL,
`user_rightEditData` TINYINT NULL,
`user_rightEditUser` TINYINT NULL,
`user_rightEditAttribute` TINYINT NULL,
`user_rightEditList` TINYINT NULL,
`user_rightDeleteData` TINYINT NULL,
`user_rightDeleteUser` TINYINT NULL,
`user_rightDeleteAttribute` TINYINT NULL,
`user_rightDeleteList` TINYINT NULL,
`user_dateCreated` DATETIME NOT NULL,
`user_createdFrom` INT NULL,
`user_dateChanged` DATETIME NULL,
`user_changedFrom` INT NULL,
`user_dateDeleted` DATETIME NULL,
`user_deletedFrom` INT NULL,
PRIMARY KEY (`ID`),
INDEX `fkCountries_idx` (`user_country` ASC),
INDEX `fkUsers_idx` (`user_rightViewData` ASC),
INDEX `fkCorporateAccounts_idx` (`user_belongsTo` ASC),
UNIQUE INDEX `ID_UNIQUE` (`ID` ASC),
INDEX `fkUsersToCreatedFrom_idx` (`user_createdFrom` ASC),
INDEX `fkUsersToChangedFrom_idx` (`user_changedFrom` ASC),
INDEX `fkUsersToDeletedFrom_idx` (`user_deletedFrom` ASC),
CONSTRAINT `fkCountries2`
FOREIGN KEY (`user_country`)
REFERENCES `profiCRM`.`countries` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkUsersToRightViewData2`
FOREIGN KEY (`user_rightViewData`)
REFERENCES `profiCRM`.`users` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkCorporateAccounts2`
FOREIGN KEY (`user_belongsTo`)
REFERENCES `profiCRM`.`corporateAccounts` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkUsersToCreatedFrom2`
FOREIGN KEY (`user_createdFrom`)
REFERENCES `profiCRM`.`users` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkUsersToChangedFrom2`
FOREIGN KEY (`user_changedFrom`)
REFERENCES `profiCRM`.`users` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkUsersToDeletedFrom2`
FOREIGN KEY (`user_deletedFrom`)
REFERENCES `profiCRM`.`users` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SHOW WARNINGS;
-- -----------------------------------------------------
-- Table `profiCRM`.`corporateAccounts`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `profiCRM`.`corporateAccounts` (
`ID` INT NOT NULL AUTO_INCREMENT,
`corporateAccount_name1` VARCHAR(45) NOT NULL,
`corporateAccount_name2` VARCHAR(45) NULL,
`corporateAccount_adress1` VARCHAR(45) NOT NULL,
`corporateAccount_adress2` VARCHAR(45) NULL,
`corporateAccount_department` VARCHAR(45) NULL,
`corporateAccount_zipcode` VARCHAR(10) NOT NULL,
`corporateAccount_city` VARCHAR(45) NOT NULL,
`corporateAccount_state` VARCHAR(45) NULL,
`corporateAccount_country` INT NOT NULL,
`corporateAccount_parentTo` INT NULL,
`corporateAccount_childOf` INT NULL,
`corporateAccount_dateCreated` DATETIME NOT NULL,
`corporateAccount_dateChanged` DATETIME NULL,
`corporateAccount_changedFrom` INT NULL,
`corporateAccount_dateDeleted` DATETIME NULL,
`corporateAccount_deletedFrom` INT NULL,
PRIMARY KEY (`ID`),
INDEX `fkCountries_idx` (`corporateAccount_country` ASC),
INDEX `fkCorporateAccounts_idx` (`corporateAccount_parentTo` ASC),
INDEX `fkUsers_idx` (`corporateAccount_changedFrom` ASC),
UNIQUE INDEX `ID_UNIQUE` (`ID` ASC),
INDEX `fkUsersDeletedFrom_idx` (`corporateAccount_deletedFrom` ASC),
INDEX `fkCorporateAccountsToChildOf1_idx` (`corporateAccount_childOf` ASC),
CONSTRAINT `fkCountries1`
FOREIGN KEY (`corporateAccount_country`)
REFERENCES `profiCRM`.`countries` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkCorporateAccountsToParentTo1`
FOREIGN KEY (`corporateAccount_parentTo`)
REFERENCES `profiCRM`.`corporateAccounts` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkUsersToChangedFrom1`
FOREIGN KEY (`corporateAccount_changedFrom`)
REFERENCES `profiCRM`.`users` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkUsersToDeletedFrom1`
FOREIGN KEY (`corporateAccount_deletedFrom`)
REFERENCES `profiCRM`.`users` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkCorporateAccountsToChildOf1`
FOREIGN KEY (`corporateAccount_childOf`)
REFERENCES `profiCRM`.`corporateAccounts` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SHOW WARNINGS;
-- -----------------------------------------------------
-- Table `profiCRM`.`accountTypes`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `profiCRM`.`accountTypes` (
`ID` INT NOT NULL AUTO_INCREMENT,
`accountType_description` VARCHAR(45) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE INDEX `ID_UNIQUE` (`ID` ASC))
ENGINE = InnoDB;
SHOW WARNINGS;
-- -----------------------------------------------------
-- Table `profiCRM`.`competition`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `profiCRM`.`competition` (
`ID` INT NOT NULL AUTO_INCREMENT,
`competition_description` VARCHAR(45) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE INDEX `ID_UNIQUE` (`ID` ASC))
ENGINE = InnoDB;
SHOW WARNINGS;
-- -----------------------------------------------------
-- Table `profiCRM`.`opportunityStage`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `profiCRM`.`opportunityStage` (
`ID` INT NOT NULL AUTO_INCREMENT,
`opportunityStage_description` VARCHAR(45) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE INDEX `ID_UNIQUE` (`ID` ASC))
ENGINE = InnoDB;
SHOW WARNINGS;
-- -----------------------------------------------------
-- Table `profiCRM`.`opportunityTypes`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `profiCRM`.`opportunityTypes` (
`ID` INT NOT NULL AUTO_INCREMENT,
`opportunityType_description` VARCHAR(45) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE INDEX `ID_UNIQUE` (`ID` ASC))
ENGINE = InnoDB;
SHOW WARNINGS;
-- -----------------------------------------------------
-- Table `profiCRM`.`products`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `profiCRM`.`products` (
`ID` INT NOT NULL AUTO_INCREMENT,
`product_description` VARCHAR(45) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE INDEX `ID_UNIQUE` (`ID` ASC))
ENGINE = InnoDB;
SHOW WARNINGS;
-- -----------------------------------------------------
-- Table `profiCRM`.`opportunities`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `profiCRM`.`opportunities` (
`ID` INT NOT NULL AUTO_INCREMENT,
`opportunity_belongsTo` INT NULL,
`opportunity_description` VARCHAR(45) NOT NULL,
`opportunity_type` INT NOT NULL,
`opportunity_stage` INT NOT NULL,
`opportunity_product` INT NOT NULL,
`opportunity_volume` INT NOT NULL,
`opportunity_dateCreated` DATETIME NOT NULL,
`opportunity_createdFrom` INT NOT NULL,
`opportunity_datePlannedClosure` DATE NOT NULL,
`opportunity_dateChanged` DATETIME NULL,
`opportunity_changedFrom` INT NULL,
`opportunity_dateClosed` DATETIME NULL,
`opportunity_closedFrom` INT NULL,
`opportunity_dateDeleted` DATETIME NULL,
`opportunity_deletedFrom` INT NULL,
PRIMARY KEY (`ID`),
INDEX `fkAccounts_idx` (`opportunity_belongsTo` ASC),
INDEX `fkOpportunityStage_idx` (`opportunity_stage` ASC),
INDEX `fkOpportunityType_idx` (`opportunity_type` ASC),
INDEX `fkProducts_idx` (`opportunity_product` ASC),
INDEX `fkUsers_idx` (`opportunity_createdFrom` ASC),
UNIQUE INDEX `ID_UNIQUE` (`ID` ASC),
INDEX `fkUsersToChangedFrom6_idx` (`opportunity_changedFrom` ASC),
INDEX `fkUsersToClosedFrom6_idx` (`opportunity_closedFrom` ASC),
INDEX `fkUsersToDeletedFrom6_idx` (`opportunity_deletedFrom` ASC),
CONSTRAINT `fkAccounts6`
FOREIGN KEY (`opportunity_belongsTo`)
REFERENCES `profiCRM`.`accounts` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkOpportunityStage6`
FOREIGN KEY (`opportunity_stage`)
REFERENCES `profiCRM`.`opportunityStage` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkOpportunityType6`
FOREIGN KEY (`opportunity_type`)
REFERENCES `profiCRM`.`opportunityTypes` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkProducts6`
FOREIGN KEY (`opportunity_product`)
REFERENCES `profiCRM`.`products` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkUsersToCreatedFrom6`
FOREIGN KEY (`opportunity_createdFrom`)
REFERENCES `profiCRM`.`users` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkUsersToChangedFrom6`
FOREIGN KEY (`opportunity_changedFrom`)
REFERENCES `profiCRM`.`users` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkUsersToClosedFrom6`
FOREIGN KEY (`opportunity_closedFrom`)
REFERENCES `profiCRM`.`users` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkUsersToDeletedFrom6`
FOREIGN KEY (`opportunity_deletedFrom`)
REFERENCES `profiCRM`.`users` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SHOW WARNINGS;
-- -----------------------------------------------------
-- Table `profiCRM`.`accounts`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `profiCRM`.`accounts` (
`ID` INT NOT NULL AUTO_INCREMENT,
`account_belongsTo` INT NOT NULL,
`account_kindOf` INT NOT NULL,
`account_name1` VARCHAR(45) NOT NULL,
`account_name2` VARCHAR(45) NULL,
`account_adress1` VARCHAR(45) NOT NULL,
`account_adress2` VARCHAR(45) NULL,
`account_zipcode` VARCHAR(45) NOT NULL,
`account_city` VARCHAR(45) NOT NULL,
`account_state` VARCHAR(45) NULL,
`account_country` INT NOT NULL,
`account_email` VARCHAR(45) NULL,
`account_telephoneFixed` VARCHAR(45) NULL,
`account_telephoneMobile` VARCHAR(45) NULL,
`account_fax` VARCHAR(45) NULL,
`account_internet` VARCHAR(45) NULL,
`account_childOf` INT NULL,
`account_parentTo` INT NULL,
`account_turnover` INT NULL,
`account_numberEmployees` INT NULL,
`account_numberSubsidaries` VARCHAR(45) NULL,
`account_generalInfo` VARCHAR(2000) NULL,
`account_competition` INT NULL,
`account_opportunities` INT NULL,
`account_dateCreated` DATETIME NULL,
`account_createdFrom` INT NULL,
`account_dateChanged` DATETIME NULL,
`account_changedFrom` INT NULL,
`account_dateDeleted` DATETIME NULL,
`account_deletedFrom` INT NULL,
PRIMARY KEY (`ID`),
INDEX `fkUsers_idx` (`account_belongsTo` ASC),
INDEX `fkCountries_idx` (`account_country` ASC),
INDEX `fkAccounts_idx` (`account_childOf` ASC),
INDEX `fkAccountTypes_idx` (`account_kindOf` ASC),
INDEX `fkCompetition_idx` (`account_competition` ASC),
INDEX `fkOpportunities_idx` (`account_opportunities` ASC),
UNIQUE INDEX `ID_UNIQUE` (`ID` ASC),
INDEX `FKUsersToCreatedFrom3_idx` (`account_createdFrom` ASC),
INDEX `fkUsersToChangedFrom3_idx` (`account_changedFrom` ASC),
INDEX `fkUsersToDeletedFrom3_idx` (`account_deletedFrom` ASC),
INDEX `fkAccountsToParentTo3_idx` (`account_parentTo` ASC),
CONSTRAINT `fkUsersToBelongsTo3`
FOREIGN KEY (`account_belongsTo`)
REFERENCES `profiCRM`.`users` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkCountries3`
FOREIGN KEY (`account_country`)
REFERENCES `profiCRM`.`countries` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkAccountsToChildOf3`
FOREIGN KEY (`account_childOf`)
REFERENCES `profiCRM`.`accounts` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkAccountTypes3`
FOREIGN KEY (`account_kindOf`)
REFERENCES `profiCRM`.`accountTypes` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkCompetition3`
FOREIGN KEY (`account_competition`)
REFERENCES `profiCRM`.`competition` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkOpportunities3`
FOREIGN KEY (`account_opportunities`)
REFERENCES `profiCRM`.`opportunities` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkUsersToCreatedFrom3`
FOREIGN KEY (`account_createdFrom`)
REFERENCES `profiCRM`.`users` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkUsersToChangedFrom3`
FOREIGN KEY (`account_changedFrom`)
REFERENCES `profiCRM`.`users` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkUsersToDeletedFrom3`
FOREIGN KEY (`account_deletedFrom`)
REFERENCES `profiCRM`.`users` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkAccountsToParentTo3`
FOREIGN KEY (`account_parentTo`)
REFERENCES `profiCRM`.`accounts` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SHOW WARNINGS;
-- -----------------------------------------------------
-- Table `profiCRM`.`formOfAdress`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `profiCRM`.`formOfAdress` (
`ID` INT NOT NULL AUTO_INCREMENT,
`formOfAdress_description` VARCHAR(45) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE INDEX `ID_UNIQUE` (`ID` ASC))
ENGINE = InnoDB;
SHOW WARNINGS;
-- -----------------------------------------------------
-- Table `profiCRM`.`contacts`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `profiCRM`.`contacts` (
`ID` INT NOT NULL AUTO_INCREMENT,
`contact_belongsTo` INT NOT NULL,
`contact_formOfAdress` INT NOT NULL,
`contact_title` VARCHAR(45) NULL,
`contact_firstName` VARCHAR(45) NOT NULL,
`contact_lastName` VARCHAR(45) NOT NULL,
`contact_function` VARCHAR(45) NOT NULL,
`contact_department` VARCHAR(45) NOT NULL,
`contact_telephoneFixed` VARCHAR(45) NULL,
`contact_telephoneMobile` VARCHAR(45) NULL,
`contact_email` VARCHAR(45) NULL,
`contact_fax` VARCHAR(45) NULL,
`contact_dateOfBirth` DATE NULL,
`contact_childOf` INT NULL,
`contact_parentTo` INT NULL,
`contact_generalInfo` VARCHAR(2000) NULL,
`contact_dateCreated` DATETIME NULL,
`contact_createdFrom` INT NULL,
`contact_dateChanged` DATETIME NULL,
`contact_changedFrom` INT NULL,
`contact_dateDeleted` DATETIME NULL,
`contact_deletedFrom` INT NULL,
PRIMARY KEY (`ID`),
INDEX `fkAccounts_idx` (`contact_belongsTo` ASC),
INDEX `fkFormOfAdress_idx` (`contact_formOfAdress` ASC),
INDEX `fkContacts_idx` (`contact_childOf` ASC),
INDEX `fkUsers_idx` (`contact_createdFrom` ASC),
UNIQUE INDEX `ID_UNIQUE` (`ID` ASC),
INDEX `fkContactsToParentTo4_idx` (`contact_parentTo` ASC),
INDEX `fkUsersToChangedFrom4_idx` (`contact_changedFrom` ASC),
INDEX `fkUsersToDeletedFrom4_idx` (`contact_deletedFrom` ASC),
CONSTRAINT `fkAccounts4`
FOREIGN KEY (`contact_belongsTo`)
REFERENCES `profiCRM`.`accounts` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkFormOfAdress4`
FOREIGN KEY (`contact_formOfAdress`)
REFERENCES `profiCRM`.`formOfAdress` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkContactsToChildOf4`
FOREIGN KEY (`contact_childOf`)
REFERENCES `profiCRM`.`contacts` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkUsersToCreatedFrom4`
FOREIGN KEY (`contact_createdFrom`)
REFERENCES `profiCRM`.`users` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkContactsToParentTo4`
FOREIGN KEY (`contact_parentTo`)
REFERENCES `profiCRM`.`contacts` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkUsersToChangedFrom4`
FOREIGN KEY (`contact_changedFrom`)
REFERENCES `profiCRM`.`users` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkUsersToDeletedFrom4`
FOREIGN KEY (`contact_deletedFrom`)
REFERENCES `profiCRM`.`users` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SHOW WARNINGS;
-- -----------------------------------------------------
-- Table `profiCRM`.`activityType`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `profiCRM`.`activityType` (
`ID` INT NOT NULL AUTO_INCREMENT,
`activityType_description` VARCHAR(45) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE INDEX `ID_UNIQUE` (`ID` ASC))
ENGINE = InnoDB;
SHOW WARNINGS;
-- -----------------------------------------------------
-- Table `profiCRM`.`activities`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `profiCRM`.`activities` (
`ID` INT NOT NULL AUTO_INCREMENT,
`activity_belongsToContact` INT NOT NULL,
`activity_belongsToUser` INT NULL,
`activity_type` INT NOT NULL,
`activity_dateStart` DATETIME NOT NULL,
`activity_dateEnde` DATETIME NOT NULL,
`activity_childOf` INT NULL,
`activity_goal` VARCHAR(2000) NOT NULL,
`activity_result` VARCHAR(2000) NULL,
`activity_todo` VARCHAR(2000) NULL,
`activity_todoTimeframe` DATE NULL,
`activity_dateCreated` DATETIME NOT NULL,
`activity_createdFrom` INT NOT NULL,
`activity_dateChanged` DATETIME NULL,
`activity_changedFrom` INT NULL,
`activity_dateClosed` DATETIME NULL,
`activity_closedFrom` INT NULL,
`activity_dateDeleted` DATETIME NULL,
`activity_deletedFrom` INT NULL,
PRIMARY KEY (`ID`),
INDEX `fkActivityTypes_idx` (`activity_type` ASC),
INDEX `fkContacts_idx` (`activity_belongsToContact` ASC),
INDEX `fkUsers_idx` (`activity_belongsToUser` ASC),
INDEX `fkActivities_idx` (`activity_childOf` ASC),
UNIQUE INDEX `ID_UNIQUE` (`ID` ASC),
INDEX `fkUserToCreatedFrom5_idx` (`activity_createdFrom` ASC),
INDEX `fkUserToChangedFrom5_idx` (`activity_changedFrom` ASC),
INDEX `fkUserToClosedFrom5_idx` (`activity_closedFrom` ASC),
INDEX `fkUserToDeletedFrom5_idx` (`activity_deletedFrom` ASC),
CONSTRAINT `fkActivityTypes5`
FOREIGN KEY (`activity_type`)
REFERENCES `profiCRM`.`activityType` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkContacts5`
FOREIGN KEY (`activity_belongsToContact`)
REFERENCES `profiCRM`.`contacts` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkUsersToBelongsToUser5`
FOREIGN KEY (`activity_belongsToUser`)
REFERENCES `profiCRM`.`users` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkActivities5`
FOREIGN KEY (`activity_childOf`)
REFERENCES `profiCRM`.`activities` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkUserToCreatedFrom5`
FOREIGN KEY (`activity_createdFrom`)
REFERENCES `profiCRM`.`users` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkUserToChangedFrom5`
FOREIGN KEY (`activity_changedFrom`)
REFERENCES `profiCRM`.`users` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkUserToClosedFrom5`
FOREIGN KEY (`activity_closedFrom`)
REFERENCES `profiCRM`.`users` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fkUserToDeletedFrom5`
FOREIGN KEY (`activity_deletedFrom`)
REFERENCES `profiCRM`.`users` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SHOW WARNINGS;
SET SQL_MODE=#OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=#OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=#OLD_UNIQUE_CHECKS;
Creating a foreign key from the four columns opportunities(opportunity_createdFrom, opportunity_changedFrom, opportunity_closedFrom, opportunity_deletedFrom) to the (non-existing) index users (ID , ID , ID , ID) doesn't make any sense. In fact, you can't create an index with duplicate columns like you try (unintentionally).
What you really want to do is to define separated foreign keys for the four columns of the opportunities table to the id column in the users table.
So I am very new to MySQL but I would like to think I that grasp a decent bit of it so far. I am struggling with the creation of the table PROJECT. I'm almost positive after my own research that it has something to do with my keys in the table. But I do not understand where the problem is or how to fix it.
The SQL queries below creates all tables for the project. I'm not sure of the problem because I only get the error code for the project for now. Any insight and advice on what causes this and how to rectify this in the code would be greatly appreciated.
CREATE TABLE IF NOT EXISTS `ebrasi1db`.`employee` (
`ssn` VARCHAR(10) NOT NULL,
`fname` VARCHAR(45) NULL DEFAULT NULL,
`minit` VARCHAR(1) NULL DEFAULT NULL,
`lname` VARCHAR(45) NULL DEFAULT NULL,
`bdate` DATE NULL DEFAULT NULL,
`address` VARCHAR(45) NULL DEFAULT NULL,
`sex` VARCHAR(1) NULL DEFAULT NULL,
`salary` INT(11) NULL DEFAULT NULL,
`superssn` VARCHAR(10) NULL DEFAULT NULL,
`dno` INT(11) NULL DEFAULT NULL,
PRIMARY KEY (`ssn`),
INDEX `superssn_idx` (`superssn` ASC),
INDEX `dno_idx` (`dno` ASC),
CONSTRAINT `superssn`
FOREIGN KEY (`superssn`)
REFERENCES `ebrasi1db`.`employee` (`ssn`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `dno`
FOREIGN KEY (`dno`)
REFERENCES `ebrasi1db`.`department` (`dnumber`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `ebrasi1db`.`department`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `ebrasi1db`.`department` (
`dnumber` INT(11) NOT NULL,
`dname` VARCHAR(45) NULL DEFAULT NULL,
`mgrssn` VARCHAR(10) NULL DEFAULT NULL,
`mgrstartdate` DATE NULL DEFAULT NULL,
PRIMARY KEY (`dnumber`),
INDEX `mgrssn_idx` (`mgrssn` ASC),
CONSTRAINT `mgrssn`
FOREIGN KEY (`mgrssn`)
REFERENCES `ebrasi1db`.`employee` (`ssn`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `ebrasi1db`.`dept_locations`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `ebrasi1db`.`dept_locations` (
`dnumber` INT(11) NOT NULL,
`dlocation` VARCHAR(45) NOT NULL,
PRIMARY KEY (`dnumber`, `dlocation`),
CONSTRAINT `dnumber`
FOREIGN KEY (`dnumber`)
REFERENCES `ebrasi1db`.`department` (`dnumber`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `ebrasi1db`.`project`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `ebrasi1db`.`project` (
`pnumber` INT(11) NOT NULL,
`pname` VARCHAR(45) NULL,
`plocation` VARCHAR(45) NULL,
`dnum` INT(11) NOT NULL,
PRIMARY KEY (`pnumber`),
INDEX `dnum_idx` (`dnum` ASC),
INDEX `plocation_idx` (`plocation` ASC),
CONSTRAINT `dnum`
FOREIGN KEY (`dnum`)
REFERENCES `ebrasi1db`.`department` (`dnumber`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `plocation`
FOREIGN KEY (`plocation`)
REFERENCES `ebrasi1db`.`dept_locations` (`dlocation`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `ebrasi1db`.`works_on`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `ebrasi1db`.`works_on` (
`essn` VARCHAR(10) NOT NULL,
`pno` INT NOT NULL,
`hours` DECIMAL(5,2) NULL,
PRIMARY KEY (`essn`, `pno`),
INDEX `pno_idx` (`pno` ASC),
CONSTRAINT `works_on_essn`
FOREIGN KEY (`essn`)
REFERENCES `ebrasi1db`.`employee` (`ssn`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `pno`
FOREIGN KEY (`pno`)
REFERENCES `ebrasi1db`.`project` (`pnumber`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `ebrasi1db`.`dependent`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `ebrasi1db`.`dependent` (
`essn` VARCHAR(10) NOT NULL,
`dependent_name` VARCHAR(45) NOT NULL,
`sex` VARCHAR(1) NULL,
`bdate` DATE NULL,
`relation` VARCHAR(45) NULL,
PRIMARY KEY (`essn`, `dependent_name`),
CONSTRAINT `dependent_essn`
FOREIGN KEY (`essn`)
REFERENCES `ebrasi1db`.`employee` (`ssn`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
Your problem lies essentially in the fact that you are trying to create a constraint to a non key column (because the referenced table has a double key).
In your table project you have:
CONSTRAINT `plocation`
FOREIGN KEY (`plocation`)
REFERENCES `dept_locations` (`dlocation`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
dept_locations.dlocation is not a key ALONE (primary key), therefore the reason you are not able to create that constraint.
You need to make the constraint for both keys from the referenced table like this:
CONSTRAINT `plocation`
FOREIGN KEY (`pnumber`, `plocation`)
REFERENCES `dept_locations` (`dnumber`, `dlocation`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
In this case you won't need the first constraint dnum as it is already referenced in dept_locations table.
Also note that you tables department and employee will not be created because one reference the other so you need to create the tables first without the constraints then apply the constraints like:
ALTER TABLE `employee` add
CONSTRAINT `dno`
FOREIGN KEY (`dno`)
REFERENCES `department` (`dnumber`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
Same for the department table and its constraint to employee
Normally you get the Error 1005 when it unable to create the foreign keys. When you are creating a foreign key constraint the parent table should be available in the database.
In your case 'employee' table has a FK to 'department' table but you are trying to create the 'employee' table before creating the 'department' table. Also the 'department' table has a FK back to 'employee' table. Therefore you are not able to create the 'department' table first. To solve this you may create the 'department' table first without FK to 'employee' table. Then create the 'employee' table and then alter the 'department' table with FK.
Here is the modified code for first two tables and follow the same pattern for rest if you get the same error.
CREATE TABLE IF NOT EXISTS `ebrasi1db`.`department` (
`dnumber` INT(11) NOT NULL,
`dname` VARCHAR(45) NULL DEFAULT NULL,
`mgrssn` VARCHAR(10) NULL DEFAULT NULL,
`mgrstartdate` DATE NULL DEFAULT NULL,
PRIMARY KEY (`dnumber`),
INDEX `mgrssn_idx` (`mgrssn` ASC))
ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `ebrasi1db`.`employee` (
`ssn` VARCHAR(10) NOT NULL,
`fname` VARCHAR(45) NULL DEFAULT NULL,
`minit` VARCHAR(1) NULL DEFAULT NULL,
`lname` VARCHAR(45) NULL DEFAULT NULL,
`bdate` DATE NULL DEFAULT NULL,
`address` VARCHAR(45) NULL DEFAULT NULL,
`sex` VARCHAR(1) NULL DEFAULT NULL,
`salary` INT(11) NULL DEFAULT NULL,
`superssn` VARCHAR(10) NULL DEFAULT NULL,
`dno` INT(11) NULL DEFAULT NULL,
PRIMARY KEY (`ssn`),
INDEX `superssn_idx` (`superssn` ASC),
INDEX `dno_idx` (`dno` ASC),
CONSTRAINT `superssn`
FOREIGN KEY (`superssn`)
REFERENCES `ebrasi1db`.`employee` (`ssn`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `dno`
FOREIGN KEY (`dno`)
REFERENCES `ebrasi1db`.`department` (`dnumber`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
alter table department add
CONSTRAINT `mgrssn`
FOREIGN KEY (`mgrssn`)
REFERENCES `ebrasi1db`.`employee` (`ssn`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
I'm trying to create these tables but I'm getting Error 1022 when creating the table cadastro_fornecedor.
I don't know where to start to solve this issue so any kind of help is welcome.
Here is the .sql:
SET #OLD_UNIQUE_CHECKS=##UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET #OLD_FOREIGN_KEY_CHECKS=##FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET #OLD_SQL_MODE=##SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Schema mydb
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `mydb` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ;
USE `mydb` ;
-- -----------------------------------------------------
-- Table `mydb`.`administrador`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`administrador` (
`id_administrador` INT NOT NULL,
`nome` VARCHAR(45) NULL,
`senha` VARCHAR(45) NULL,
`CPF` INT NULL,
`endereço` VARCHAR(45) NULL,
`data_nascimento` DATE NULL,
PRIMARY KEY (`id_administrador`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`cadastro_usuario`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`cadastro_usuario` (
`id_cadastro` INT NOT NULL AUTO_INCREMENT,
`data_cadastro` DATETIME NOT NULL,
`id_administrador` INT NULL,
`usuario` INT NULL,
PRIMARY KEY (`id_cadastro`),
INDEX `id_administrador_idx` (`id_administrador` ASC),
INDEX `matricula_idx` (`usuario` ASC),
CONSTRAINT `id_administrador`
FOREIGN KEY (`id_administrador`)
REFERENCES `mydb`.`administrador` (`id_administrador`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `matricula`
FOREIGN KEY (`usuario`)
REFERENCES `mydb`.`usuario_cadastrado` (`matricula`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`usuario_cadastrado`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`usuario_cadastrado` (
`matricula` INT NOT NULL,
`nome` VARCHAR(45) NULL,
`endereco` VARCHAR(45) NULL,
`senha` VARCHAR(45) NULL,
`nacionalidade` VARCHAR(45) NULL DEFAULT 'brasileiro',
`naturalidade` VARCHAR(45) NULL,
`sexo` CHAR NULL,
`data_nascimento` DATE NULL,
`CPF` INT NULL,
`nome_pai` VARCHAR(45) NULL,
`nome_mae` VARCHAR(45) NULL,
`telefone_celular` VARCHAR(15) NULL,
`telefone_fixo` VARCHAR(15) NULL,
`id_cadastro` INT NULL,
PRIMARY KEY (`matricula`),
INDEX `id_cadastro_idx` (`id_cadastro` ASC),
CONSTRAINT `id_cadastro`
FOREIGN KEY (`id_cadastro`)
REFERENCES `mydb`.`cadastro_usuario` (`id_cadastro`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`obra`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`obra` (
`ISBN` VARCHAR(20) NOT NULL,
`titulo` VARCHAR(45) NULL,
`autor` VARCHAR(45) NULL,
`ano` YEAR NULL,
`editora` VARCHAR(45) NULL,
`categoria` VARCHAR(45) NULL,
`assunto` VARCHAR(45) NULL,
`descricao` VARCHAR(45) NULL,
PRIMARY KEY (`ISBN`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`fornecedores`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`fornecedores` (
`CNPJ` VARCHAR(45) NOT NULL,
`nome` VARCHAR(45) NOT NULL,
`endereco` VARCHAR(45) NULL,
`telefone` VARCHAR(45) NULL,
PRIMARY KEY (`CNPJ`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`exemplar`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`exemplar` (
`codigo_exemplar` INT NOT NULL,
`data_aquisicao` DATE NULL,
`edição` INT NULL,
`volume` INT NULL,
`paginas` INT NULL,
`ISBN` VARCHAR(20) NULL,
`CNPJ` VARCHAR(45) NULL,
PRIMARY KEY (`codigo_exemplar`),
INDEX `ISBN_idx` (`ISBN` ASC),
INDEX `CNPJ_idx` (`CNPJ` ASC),
CONSTRAINT `ISBN`
FOREIGN KEY (`ISBN`)
REFERENCES `mydb`.`obra` (`ISBN`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `CNPJ`
FOREIGN KEY (`CNPJ`)
REFERENCES `mydb`.`fornecedores` (`CNPJ`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`cadastro_fornecedor`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`cadastro_fornecedor` (
`id_cadastro` INT NOT NULL AUTO_INCREMENT,
`data` DATETIME NULL,
`id_administrador` INT NULL,
`CNPJ` VARCHAR(45) NULL,
PRIMARY KEY (`id_cadastro`),
INDEX `id_administrador_idx` (`id_administrador` ASC),
INDEX `CNPJ_idx` (`CNPJ` ASC),
CONSTRAINT `id_administrador`
FOREIGN KEY (`id_administrador`)
REFERENCES `mydb`.`administrador` (`id_administrador`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `CNPJ`
FOREIGN KEY (`CNPJ`)
REFERENCES `mydb`.`fornecedores` (`CNPJ`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`emprestimo`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`emprestimo` (
`id_emprestimo` INT NOT NULL AUTO_INCREMENT,
`data_emprestimo` DATE NULL,
`data_devolucao_prevista` DATE NULL,
`matricula` INT NULL,
`id_administrador` INT NULL,
`codigo_exemplar` INT NULL,
PRIMARY KEY (`id_emprestimo`),
INDEX `matricula_idx` (`matricula` ASC),
INDEX `id_administrador_idx` (`id_administrador` ASC),
INDEX `codigo_exemplar_idx` (`codigo_exemplar` ASC),
CONSTRAINT `matricula`
FOREIGN KEY (`matricula`)
REFERENCES `mydb`.`usuario_cadastrado` (`matricula`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `id_administrador`
FOREIGN KEY (`id_administrador`)
REFERENCES `mydb`.`administrador` (`id_administrador`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `codigo_exemplar`
FOREIGN KEY (`codigo_exemplar`)
REFERENCES `mydb`.`exemplar` (`codigo_exemplar`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`devolucao`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`devolucao` (
`id_devolucao` INT NOT NULL,
`data_devolucao` DATE NULL,
`multa` INT NULL,
`matricula` INT NULL,
`id_administrador` INT NULL,
PRIMARY KEY (`id_devolucao`),
INDEX `matricula_idx` (`matricula` ASC),
INDEX `id_administrador_idx` (`id_administrador` ASC),
CONSTRAINT `matricula`
FOREIGN KEY (`matricula`)
REFERENCES `mydb`.`usuario_cadastrado` (`matricula`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `id_administrador`
FOREIGN KEY (`id_administrador`)
REFERENCES `mydb`.`administrador` (`id_administrador`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`exclusao`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`exclusao` (
`id_exclusao` INT NOT NULL AUTO_INCREMENT,
`data_exclusao` DATE NULL,
`id_administrador` INT NULL,
`codigo_exemplar` INT NULL,
PRIMARY KEY (`id_exclusao`),
INDEX `id_administrador_idx` (`id_administrador` ASC),
INDEX `codigo_exemplar_idx` (`codigo_exemplar` ASC),
CONSTRAINT `id_administrador`
FOREIGN KEY (`id_administrador`)
REFERENCES `mydb`.`administrador` (`id_administrador`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `codigo_exemplar`
FOREIGN KEY (`codigo_exemplar`)
REFERENCES `mydb`.`exemplar` (`codigo_exemplar`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`registro`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`registro` (
`id_registro` INT NOT NULL AUTO_INCREMENT,
`data_registro` DATE NULL,
`id_administrador` INT NULL,
`codigo_exemplar` INT NULL,
PRIMARY KEY (`id_registro`),
INDEX `id_administrador_idx` (`id_administrador` ASC),
INDEX `codigo_exemplar_idx` (`codigo_exemplar` ASC),
CONSTRAINT `id_administrador`
FOREIGN KEY (`id_administrador`)
REFERENCES `mydb`.`administrador` (`id_administrador`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `codigo_exemplar`
FOREIGN KEY (`codigo_exemplar`)
REFERENCES `mydb`.`exemplar` (`codigo_exemplar`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `mydb`.`reserva`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`reserva` (
`id_reserva` INT NOT NULL,
`data_reserva` DATE NULL,
`matricula` INT NULL,
`ISBN` VARCHAR(20) NULL,
PRIMARY KEY (`id_reserva`),
INDEX `matricula_idx` (`matricula` ASC),
INDEX `ISBN_idx` (`ISBN` ASC),
CONSTRAINT `matricula`
FOREIGN KEY (`matricula`)
REFERENCES `mydb`.`usuario_cadastrado` (`matricula`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `ISBN`
FOREIGN KEY (`ISBN`)
REFERENCES `mydb`.`obra` (`ISBN`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SET SQL_MODE=#OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=#OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=#OLD_UNIQUE_CHECKS;
I appreciate any kind of help.
Thanks.
You're reusing existing constraint names (id_administrador is already used as a constraint name in the table cadastro_usuario and CNPJ is used in the table exemplar), you'll have to give your constraints unique names (here I renamed them to cf_id_administrador/CF_CNPJ);
-- -----------------------------------------------------
-- Table `mydb`.`cadastro_fornecedor`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `mydb`.`cadastro_fornecedor` (
`id_cadastro` INT NOT NULL AUTO_INCREMENT,
`data` DATETIME NULL,
`id_administrador` INT NULL,
`CNPJ` VARCHAR(45) NULL,
PRIMARY KEY (`id_cadastro`),
INDEX `id_administrador_idx` (`id_administrador` ASC),
INDEX `CNPJ_idx` (`CNPJ` ASC),
CONSTRAINT `cf_id_administrador`
FOREIGN KEY (`id_administrador`)
REFERENCES `mydb`.`administrador` (`id_administrador`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `CF_CNPJ`
FOREIGN KEY (`CNPJ`)
REFERENCES `mydb`.`fornecedores` (`CNPJ`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;