Cannot add foreign key constraint in phpmyadmin - mysql - mysql

I have a table called teachers. I cannot use the id from teachers to create a composite table in slot table with the following query.
CREATE TABLE `teachers` (
`id` bigint(20) UNSIGNED NOT NULL,
`first_name` varchar(255) NOT NULL,
`last_name` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
);
ALTER TABLE `teachers`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `teachers_email_unique` (`email`);
to create slot table
CREATE TABLE `slot` (
`teacher_id` bigint(20) NOT NULL,
`is_confirmed` tinyint(1) NOT NULL,
PRIMARY kEY (`teacher_id`),
foreign key (`teacher_id`) references `teachers`(`id`) on delete CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Data type of the referencing and referenced fields, should be exactly the same while defining a Foreign Key constraint. In your teachers table, id is BIGINT UNSIGNED, while in your slot table, it is BIGINT only. Add UNSIGNED clause as well:
CREATE TABLE `slot` (
`teacher_id` bigint(20) UNSIGNED NOT NULL,
`is_confirmed` tinyint(1) NOT NULL,
PRIMARY kEY (`teacher_id`),
foreign key (`teacher_id`) references `teachers`(`id`) on delete CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Related

How to fix 'MySQL Error: 1822. Missing index for contraint' On creating a composite foreign key

I'm trying to create a table with a composite foreign key, but keep getting met with the error Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint 'fk_contractdateshistoric_contractdates_multiple' in the referenced table 'contractdates'
I'm using MySQL v8.0.16
I've checked if the column types are different, and I'm not sure what else could be the problem.
Here are the tables that make up the problem, All tables are made happily but the last one that contains the composite key causes the problem.
CREATE TABLE `contracts` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(100) DEFAULT NULL,
`CreationDate` datetime DEFAULT NULL,
`CreatedBy` varchar(30) DEFAULT NULL,
`CompletionDate` date DEFAULT NULL,
`Comments` varchar(100) DEFAULT NULL,
PRIMARY KEY (`ID`)
);
CREATE TABLE `fieldheading` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`fieldTypeID` int(11) DEFAULT NULL,
`fieldCode` int(11) DEFAULT NULL,
`fieldHeading` varchar(100) DEFAULT NULL,
PRIMARY KEY (`ID`)
);
CREATE TABLE `contractdates` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`DateValue` datetime DEFAULT NULL,
`ContractID` int(11) NOT NULL,
`FieldHeadingID` int(11) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `uq_contractdates_contractID_FieldHeading_ID` (`ContractID`,`FieldHeadingID`),
KEY `fk_contractdates_contracts_id_idx` (`ContractID`),
KEY `fk_contractdates_fieldheading_id_idx` (`FieldHeadingID`),
CONSTRAINT `fk_contractdates_fieldheading_id` FOREIGN KEY (`FieldHeadingID`) REFERENCES `fieldheading` (`id`),
CONSTRAINT `fk_contractdates_contracts_id` FOREIGN KEY (`ContractID`) REFERENCES `contracts` (`id`)
) COMMENT='Table to hold the dates for a contract, one row is one date for a specific contract';
CREATE TABLE `contractdateshistoric` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`ContractID` int(11) NOT NULL,
`ContractDateCurrentID` int(11) NOT NULL,
`FieldHeadingID` int(11) NOT NULL,
`ChangedByID` int(11) NOT NULL,
`DateValue` datetime NOT NULL,
`TimeStampChanged` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`ID`),
KEY `fk_contractdateshistoric_contractdates_mutiple_idx` (`ContractID`, `FieldHeadingID`, `ContractDateCurrentID`),
CONSTRAINT `fk_contractdateshistoric_contractdates_multiple` FOREIGN KEY (`ContractID`, `FieldHeadingID`, `ContractDateCurrentID`) REFERENCES `contractdates` (`contractid`, `fieldheadingid`, `id`)
) COMMENT='Audit trail of the dates';
Since you are using Composite FK in the table contractdates try adding composite index as well
KEY `fk_contractdates_mutiple_idx` (`ContractID`,`FieldHeadingID`,`ID`)
Whole create statement
CREATE TABLE `contractdates` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`DateValue` datetime DEFAULT NULL,
`ContractID` int(11) NOT NULL,
`FieldHeadingID` int(11) NOT NULL,
PRIMARY KEY (`ID`),
KEY `fk_contractdates_contracts_id_idx` (`ContractID`),
KEY `fk_contractdates_fieldheading_id_idx` (`FieldHeadingID`),
KEY `fk_contractdates_mutiple_idx` (`ContractID`,`FieldHeadingID`,`ID`),
CONSTRAINT `fk_contractdates_fieldheading_id` FOREIGN KEY (`FieldHeadingID`) REFERENCES `fieldheading` (`id`),
CONSTRAINT `fk_contractdates_contracts_id` FOREIGN KEY (`ContractID`) REFERENCES `contracts` (`id`)
) COMMENT='Table to hold the dates for a contract, one row is one date for a specific contract';
It's trying to tell you "you haven't created a necessary unique index on contractdates, that covers the columns (contractid, fieldheadingid, id) so I cannot create a foreign key on contractdateshistoric that refers to this set of columns when determining the single parent row"
I'm not sure why you're creating an fk that references 3 columns when contractdates has a pk that is just the ID column.
If a contractdateshistoric records refers to a single contractdates record as its parent, the historic record should have a contractdateid column that refers to contractdates.id - no need for multiple columns. Copy the pattern you used to relate a contractdates to its parent contract, and you'll be fine
I have tried by creating the keys individually for the columns, Please find the updated query:
CREATE TABLE `contractdateshistoric` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`ContractID` INT(11) NOT NULL,
`ContractDateCurrentID` INT(11) NOT NULL,
`FieldHeadingID` INT(11) NOT NULL,
`ChangedByID` INT(11) NOT NULL,
`DateValue` DATETIME NOT NULL,
`TimeStampChanged` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`ID`),
KEY `fk_contractdateshistoric_contractdates_mutiple_idx` (`ContractID`),
KEY `fk_contractdateshistoric_contractdates_mutiple_idx1` (`FieldHeadingID`),
KEY `fk_contractdateshistoric_contractdates_mutiple_idx2` (`ContractDateCurrentID`),
CONSTRAINT `fk_contractdateshistoric_contractdates_multiple` FOREIGN KEY (`ContractID`)
REFERENCES `contractdates` (`contractid`),
CONSTRAINT `fk_contractdateshistoric_contractdates_multiple1` FOREIGN KEY (`FieldHeadingID`)
REFERENCES `contractdates` (`fieldheadingid`),
CONSTRAINT `fk_contractdateshistoric_contractdates_multiple2` FOREIGN KEY (`ContractDateCurrentID`)
REFERENCES `contractdates` (`id`)
);
It works fine.

MySQL UNIQUE KEY and FOREIGN KEY same column not getting created

I have following tables/CREATE sintaxis:
CREATE TABLE `users` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`parentId` int(10) unsigned DEFAULT NULL,
`fullName` varchar(50) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`alias` varchar(35) COLLATE utf8_unicode_ci DEFAULT NULL,
`username` varchar(50) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
`password` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_username` (`username`),
UNIQUE KEY `uk_parentId_fullName_alias` (`parentId`,`fullName`,`alias`),
KEY `fk_users_parentId` (`parentId`),
CONSTRAINT `fk_users_parentId` FOREIGN KEY (`parentId`) REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `userSettings` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`userId` int(11) unsigned NOT NULL,
`settingsArray` text NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_userId` (`userId`),
KEY `fk_userSettings_userId` (`userId`),
CONSTRAINT `fk_userSettings_userId` FOREIGN KEY (`userId`) REFERENCES `users` (`id`) ON DELETE CASCADE
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1
im trying to create one table with user data and another one with the user settings, when i create the userSettings table it doesnt create the foreign key, is there something wrong with the create sintaxis? It is related with creating two indexes for same column?
Here what i get after creating the userSettings table:
CREATE TABLE `userSettings` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`userId` int(11) unsigned NOT NULL,
`settingsArray` text NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_userId` (`userId`),
KEY `fk_userSettings_userId` (`userId`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
As you discovered, MyISAM doesn't support foreign keys. Both users and userSettings must be InnoDB.
[I'm] just curious if having a UNIQUE_KEY and FOREIGN_KEY in same column is a good practice
This means the userSettings table can have at most one row for each userId. I guess you need only one row per userId because you store an "array" of settings encoded somehow in your settingsArray TEXT column. This is not a good practice.
You should either store each setting in its own column:
CREATE TABLE `userSettings` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`userId` int(11) unsigned NOT NULL,
`isAdmin` bool NOT NULL,
`timezone` varchar(10) NOT NULL,
`theme` varchar(10) NOT NULL,
...other settings...
PRIMARY KEY (`id`),
UNIQUE KEY `uk_userId` (`userId`),
KEY `fk_userSettings_userId` (`userId`)
)
Or else store multiple rows per userId, with one setting name and value per row.
CREATE TABLE `userSettings` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`userId` int(11) unsigned NOT NULL,
`setting` varchar(20) NOT NULL,
`value` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_userId` (`userId`,`setting`),
KEY `fk_userSettings_userId` (`userId`)
)
It's also puzzling why you need an id column for the primary key, if the userId is already NOT NULL and UNIQUE, and that's probably the key you'll use to look up rows anyway. You can make the userId the PRIMARY KEY as well (or userId, setting in the second example), and omit the id column.
Just realized for the table users the ENGINE was InnoDB and for the userSettings table ENGINE was MyISAM, changed that and worked, im just curious if having a UNIQUE_KEY and FOREIGN_KEY in same column is a good practice

MySQL Foreign key error 1215, even though both colums are of the same type and are NOT NULL

Parent table team_entrant:
CREATE TABLE IF NOT EXISTS `team_entrant` (
`entrant_number` tinyint(4) NOT NULL,
`qualifying_position` tinyint(4) NOT NULL,
`qualifying_time` time(3) NOT NULL,
`grid_position` tinyint(4) DEFAULT NULL,
`best_race_time` datetime DEFAULT NULL,
`final_position` tinyint(4) DEFAULT NULL,
`dnf_reason` varchar(45) DEFAULT NULL,
`team_id` int(11) NOT NULL,
`competition_year` date NOT NULL,
PRIMARY KEY (`entrant_number`),
KEY `fk_team_entrant_team1_idx` (`team_id`),
CONSTRAINT `fk_team_entrant_team1` FOREIGN KEY (`team_id`) REFERENCES `team` (`team_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Child table/Associative table entrant_drivers:
CREATE TABLE IF NOT EXISTS `entrant_drivers` (
`entrant_number` tinyint(4) NOT NULL,
`competition_year` date NOT NULL,
`driver_id` int(11) NOT NULL,
PRIMARY KEY (`entrant_number`,`competition_year`,`driver_id`),
CONSTRAINT `ed_entrant_fk` FOREIGN KEY (`entrant_number`) REFERENCES `team_entrant` (`entrant_number`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
At the time the team_entrant column competition_year did not exist.
HeidiSQL refuses to execute the following code:
ALTER table entrant_drivers ADD CONSTRAINT ed_comp_year_fk FOREIGN KEY (competition_year) REFERENCES team_entrant(competition_year);
SQL Error (1215): Cannot add foreign key constraint
Extraneous table, driver involved with the associative table:
-- Dumping structure for table 99_lemans_db1.driver
CREATE TABLE IF NOT EXISTS `driver` (
`driver_id` int(11) NOT NULL,
`driver_name` varchar(64) NOT NULL,
`driver_nationality` varchar(32) NOT NULL,
`driver_birth_day` date NOT NULL,
`driver_best_previous_finish_class` varchar(8) DEFAULT NULL,
`driver_best_previous_finish_position` tinyint(4) DEFAULT NULL,
`team_entrant_id` int(11) NOT NULL,
PRIMARY KEY (`driver_id`,`team_entrant_id`),
KEY `fk_driver_team_entrant1_idx` (`team_entrant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Any assistance would be appreciated.
The parent column must be designated as an index/primary key.
team_entrant is supposed to be made up of the composite primary keys (entrant number, competition year).

Cannot add foreign key constraint in MySQL with FOREIGN KEY

I just created this table:
CREATE TABLE `t_application` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`application_desc` varchar(255) DEFAULT NULL,
`application_key` varchar(50) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `UK_cotl49evfo7w4plf6213uaruc` (`application_key`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Then I want to create this one:
CREATE TABLE `t_device` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`device_key` varchar(50) DEFAULT NULL,
`device_type` varchar(50) DEFAULT NULL,
`application_id` int(11) unsigned NOT NULL,
`device_desc` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `application_id` (`application_id`),
CONSTRAINT `t_device_app` FOREIGN KEY (`application_id`) REFERENCES `t_application` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
but its not possible because I got this error:
Cannot add foreign key constraint
The FK column has to have the same type as PK in referenced table:
Using FOREIGN KEY Constraints
Corresponding columns in the foreign key and the referenced key must
have similar data types. The size and sign of integer types must be
the same. The length of string types need not be the same. For
nonbinary (character) string columns, the character set and collation
must be the same.
You have: int(11) <> int(11) unsigned
CREATE TABLE `t_application` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`application_desc` varchar(255) DEFAULT NULL,
`application_key` varchar(50) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `UK_cotl49evfo7w4plf6213uaruc` (`application_key`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `t_device` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`device_key` varchar(50) DEFAULT NULL,
`device_type` varchar(50) DEFAULT NULL,
`application_id` int(11) unsigned NOT NULL,
`device_desc` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `application_id` (`application_id`),
CONSTRAINT `t_device_app` FOREIGN KEY (`application_id`)
REFERENCES `t_application` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
SqlFiddleDemo
So you can change: t_application.id to int(11) unsigned
or t_device.application_id to int(11)

mysql add foreign key constraint error

I have two tables which I'd like to connect with foreign key constraint
For some reason, when I try to do it, it fails and and says: #1215 - Cannot add foreign key constraint
Here is my first table:
CREATE TABLE `zmaneyhayom` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`zman_id` varchar(255) NOT NULL,
`tempHour` tinyint(1) NOT NULL,
`tempHourType` varchar(255) NOT NULL,
`tempHourNum` double NOT NULL,
`tempMinutes` tinyint(1) NOT NULL,
`tempMinutesType` varchar(255) NOT NULL,
`tempMinutesNum` double NOT NULL,
`regularMinutes` tinyint(1) NOT NULL,
`regularMinutesNum` double NOT NULL,
`equivalentMinutes` tinyint(1) NOT NULL,
`equivalentMinutesNum` double NOT NULL,
`degreesBelowHorizon` tinyint(1) NOT NULL,
`degreesBelowHorizonNum` double NOT NULL,
`beforeAfter` varchar(6) NOT NULL,
`riseSet` varchar(4) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `zman_id_2` (`zman_id`),
KEY `zman_id` (`zman_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
And this table holds ID and name, which eventually the ID in this table is the name for the previous table (zman_id column):
CREATE TABLE `zmaneyhayomlabels` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
This is the code I'm attempting in order to create the constraint:
ALTER TABLE `zmaneyhayom` ADD FOREIGN KEY ( `zman_id` ) REFERENCES `luah_v2`.`zmaneyhayomlabels` (
`id`
) ON DELETE NO ACTION ON UPDATE NO ACTION ;
I have no idea why it's failing :/
What I want is that whenever I go on phpmyadmin and go to the first table, instead of typing some id in zman_id I will have a select box which I can select a name (which is stored in the second table) but the value it will store will be the ID.
they are not same type id is INT and zman_id is varchar.
you can change this
`zman_id` varchar(255) NOT NULL,
to
`zman_id` int(11) NOT NULL,