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

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).

Related

Cannot add foreign key constraint in phpmyadmin - 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;

ERROR 1215: Cannot add foreign key constraint (multiple column FK)

I'm going crazy trying to figure out the reason of the well-known ERROR 1215 (MySQL 6.3.5).
I have to declare a table with a four-column PK, in which 3 of the columns are FK referencing other table.
CREATE TABLE `zen`.`pago_abono` (
`fecha_pago` DATETIME NOT NULL,
`cod_abono` VARCHAR(4) NOT NULL,
`mes` INT(2) NOT NULL,
`anio` YEAR NOT NULL,
`monto_pago` DECIMAL(10,2) NULL,
PRIMARY KEY (`fecha_pago`, `cod_abono`, `mes`, `anio`),
INDEX `cuota_fk_idx` (`mes` ASC, `anio` ASC, `cod_abono` ASC),
CONSTRAINT `cuota_fk`
FOREIGN KEY (`mes` , `anio` , `cod_abono`)
REFERENCES `zen`.`cuota_abono` (`mes` , `anio` , `cod_abono`)
ON DELETE NO ACTION
ON UPDATE NO ACTION);
"cuota_fk" references the table "cuota_abono"
CREATE TABLE `cuota_abono` (
`cod_abono` varchar(4) NOT NULL,
`mes` int(2) NOT NULL,
`anio` year(4) NOT NULL,
`valor` decimal(10,2) DEFAULT NULL,
PRIMARY KEY (`cod_abono`,`anio`,`mes`),
CONSTRAINT `cod_abono_fk` FOREIGN KEY (`cod_abono`) REFERENCES `abonos`(`cod_abono`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Finally, "cuota_abono" has a FK, "cod_abono_fk", referencing "abonos"
CREATE TABLE `abonos` (
`cod_abono` varchar(4) NOT NULL,
`direccion` varchar(45) NOT NULL,
`tel_verificacion` varchar(45) NOT NULL,
`fecha_alta` date DEFAULT NULL,
`descripcion` varchar(45) DEFAULT NULL,
`cuenta_cte` decimal(10,2) DEFAULT '0.00',
`cod_localidad` varchar(3) DEFAULT NULL,
`cod_cobrador` varchar(3) DEFAULT NULL,
`nombre_servicio` varchar(45) DEFAULT NULL,
PRIMARY KEY (`cod_abono`),
KEY `zona_cobranza_fk_idx` (`cod_localidad`,`cod_cobrador`),
CONSTRAINT `zona_cobranza_fk` FOREIGN KEY (`cod_localidad`, `cod_cobrador`) REFERENCES `zonas_cobranza` (`cod_localidad`, `cod_cobrador`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Can you find the mistake?
Thanks!
P.S.: All tables have already been created, except from "pago_abono". I'm showing the CREATE statement of tables "abonos" and "cuota_abono" just to let you know their structure.
I even tried creating "pago_abono" just with the PK and then used ALTER to add the FKs, but it still shows the error.

"Foreign key contraint" error message although there are no foreign keys

I am trying to change the engine for my table "adverts". It does not let me and I get the message that "a foreign key contraint fails". But I removed all foreign keys and SHOW CREATE TABLE gives me this:
CREATE TABLE `adverts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`id_users` int(11) NOT NULL,
`id_categories_adverts` int(11) NOT NULL,
`type` int(11) NOT NULL,
`status` int(11) NOT NULL,
`duration` int(11) NOT NULL,
`headline` varchar(200) NOT NULL,
`description` text NOT NULL,
`show_contact` int(11) NOT NULL,
`stamp_created` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`stamp_updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8
Why can't I change the engine of my table? I am using
ALTER TABLE adverts ENGINE=MyISAM
The problem is that there is at least another table with foreign key to your adverts table. You need to tackle with those foreign key constraints, possibly, by temporarily/permanently removing them.

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,

Error 1050 when trying to add foreign key constraing in MySQL

I have tried adding a column to my UserOrder table called discountcode. This is a nullable foreign key into
alter table UserOrder add column discountCode varchar(100) null;
alter table UserOrder add foreign key FK_UserOrder_DiscountCode_code(`discountCode`) references DiscountCode(`code`);
The error happens on the second line. Both tables are running InnoDB. I am on MySQL 5.5.11.
Here is the error log...
[2012-05-29 23:59:07] [42S01][1050] Table '.\realtorprint_dev_dev\userorder' already exists
[2012-05-29 23:59:07] [HY000][1025] Error on rename of '.\realtorprint_dev_dev\#sql-28a4_3' to '.\realtorprint_dev_dev\userorder' (errno: -1)
[2012-05-29 23:59:07] [42S01][1050] Table '.\realtorprint_dev_dev\userorder' already exists
Here is "show create Table UserOrder"
'CREATE TABLE `userorder` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`created` datetime NOT NULL,
`paymentTxID` varchar(255) DEFAULT NULL,
`shippedDate` datetime DEFAULT NULL,
`shippingTrackingNumber` varchar(255) DEFAULT NULL,
`taxType` varchar(255) NOT NULL,
`taxValue` decimal(10,2) NOT NULL,
`orderStatus` varchar(50) NOT NULL,
`user_id` bigint(20) NOT NULL,
`address` varchar(255) NOT NULL,
`city` varchar(255) NOT NULL,
`country` varchar(255) NOT NULL,
`stateProvince` varchar(255) NOT NULL,
`zipPostal` varchar(255) NOT NULL,
`paymentType` varchar(255) NOT NULL,
`backendUserId` bigint(20) DEFAULT NULL,
`adjustedTotalPrice` decimal(10,2) DEFAULT NULL,
`adjustedPrinterPrice` decimal(10,2) DEFAULT NULL,
`adminNotes` varchar(2048) DEFAULT NULL,
`printerBillStatus` varchar(40) NOT NULL,
`userInvoiceStatus` varchar(40) NOT NULL,
`expeditedAddressDescription` varchar(255) DEFAULT NULL,
`shippingType` varchar(50) NOT NULL,
`shippingCost` decimal(10,2) NOT NULL,
`discountCode` varchar(100) DEFAULT NULL,
`discountAmount` decimal(10,2) NOT NULL,
PRIMARY KEY (`id`),
KEY `idx_UserOrder_user_id` (`user_id`),
KEY `idx_UserOrder_orderStatus_id` (`orderStatus`),
KEY `FK_UserOrder_PaymentType` (`paymentType`),
KEY `FK_UserOrder_PrinterBillStatus_Name` (`printerBillStatus`),
KEY `FK_UserOrder_UserInvoiceStatus_Name` (`userInvoiceStatus`),
KEY `FK_UserOrder_User` (`backendUserId`),
KEY `FK_UserOrder_ShippingType_name` (`shippingType`),
CONSTRAINT `FK_UserOrderBcknd_User` FOREIGN KEY (`backendUserId`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `FK_UserOrder_user_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`),
CONSTRAINT `userorder_ibfk_1` FOREIGN KEY (`shippingType`) REFERENCES `shippingtype` (`name`),
CONSTRAINT `UserOrder_ibfk_2` FOREIGN KEY (`paymentType`) REFERENCES `paymenttype` (`name`),
CONSTRAINT `UserOrder_ibfk_6` FOREIGN KEY (`printerBillStatus`) REFERENCES `printerbillstatus` (`name`),
CONSTRAINT `UserOrder_ibfk_7` FOREIGN KEY (`userInvoiceStatus`) REFERENCES `userinvoicestatus` (`name`),
CONSTRAINT `UserOrder_ibfk_8` FOREIGN KEY (`orderStatus`) REFERENCES `orderstatus` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=21412 DEFAULT CHARSET=utf8'
Here is show create table DiscountCode...
'CREATE TABLE `discountcode` (
`code` varchar(100) NOT NULL,
`percent` int(11) NOT NULL,
`created` datetime NOT NULL,
`expires` datetime NOT NULL,
`maxUses` int(11) NOT NULL,
`useCount` int(11) NOT NULL,
PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8'
As stated in the manual:
InnoDB requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index is created on the referencing table automatically if it does not exist. This index might be silently dropped later, if you create another index that can be used to enforce the foreign key constraint. index_name, if given, is used as described previously.
Have you defined an index on the referenced key DiscountCode.code?