MySql Define foreign key with multiple columns throws error - mysql

I have 2 tables. And queries are below.
CREATE TABLE `queue_service_settings` (
`app_id` int(11) NOT NULL,
`app_id_type` int(11) NOT NULL,
`channel_id` int(11) NOT NULL,
`setting_type` varchar(255) NOT NULL,
`setting_key` varchar(255) NOT NULL,
`setting_value` varchar(255) NOT NULL,
`update_time` datetime DEFAULT CURRENT_TIMESTAMP,
`create_time` datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (app_id,app_id_type),
KEY `index_qss_app_id` (`app_id`) USING BTREE,
KEY `index_qss_setting_type` (`setting_type`) USING BTREE,
KEY `index_qss_setting_key` (`setting_key`) USING BTREE,
KEY `index_qss_channel_id` (`channel_id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `queue_applications` (
`app_id` int(11) NOT NULL,
`app_id_type` int(11) NOT NULL,
`channel_id` int(11) NOT NULL,
`app_name` varchar(255) NOT NULL,
`callback_url` varchar(255) NOT NULL,
`update_time` datetime DEFAULT CURRENT_TIMESTAMP,
`create_time` datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`app_id`,`app_id_type`,`channel_id`),
KEY `fk_qa_channel_id` (`channel_id`),
CONSTRAINT `fk_qa_app_id_app_id_type_channel_id` FOREIGN KEY (app_id,app_id_type,channel_id) REFERENCES queue_service_settings(app_id,app_id_type,channel_id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
And i am getting this error
Cannot add foreign key constraint Create table
'event_processor_test/queue_applications' with foreign key constraint
failed. There is no index in the referenced table where the referenced
columns appear as the first columns.
When i tried to define this 3 columns (app_id,app_id_type,channel_id) as primary key its ok but primary key should be just (app_id,app_id_type)

The columns in the foreign key must match the columns of the primary key referenced in the other table. You have two columns in the primary key of queue_service_settings, so you should have two columns in the foreign key that references it.
CREATE TABLE `queue_applications` (
`app_id` int(11) NOT NULL,
`app_id_type` int(11) NOT NULL,
`channel_id` int(11) NOT NULL,
`app_name` varchar(255) NOT NULL,
`callback_url` varchar(255) NOT NULL,
`update_time` datetime DEFAULT CURRENT_TIMESTAMP,
`create_time` datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`app_id`,`app_id_type`,`channel_id`),
KEY `fk_qa_channel_id` (`channel_id`),
CONSTRAINT `fk_qa_app_id_app_id_type_channel_id`
FOREIGN KEY (app_id,app_id_type)
REFERENCES queue_service_settings(app_id,app_id_type)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Related

Insert into table results in "column cannot be null" but said column does not exist

I have a SQL table that when I try to insert a row into it I get
Error Code: 1048. Column 'chave_integracao_grupo' cannot be null
The table does not have a column named "chave_integracao_grupo".
I tried inserting data into said column but got the standard column does not exist error. I also checked and All the NOT NULL columns are receiving a default expressions.
Edit:
CREATE TABLE `empresas` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`id_grupo` int(11) NOT NULL DEFAULT '1',
`cnpj` varchar(18) DEFAULT NULL,
`id_estado` int(11) DEFAULT NULL,
`id_cidade` int(11) DEFAULT NULL,
`id_funcionalidade` int(11) NOT NULL DEFAULT '3',
`inscricao_estadual` varchar(15) DEFAULT NULL,
`razao_social` varchar(100) NOT NULL,
`nome_fantasia` varchar(50) NOT NULL,
`telefone` varchar(20) DEFAULT NULL,
`cep` varchar(12) DEFAULT NULL,
`endereco` varchar(50) DEFAULT NULL,
`bairro` varchar(50) DEFAULT NULL,
`numero` varchar(10) DEFAULT NULL,
`status` tinyint(4) NOT NULL DEFAULT '1',
`id_integracao_gerencial` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FK_EMPRESAS_CIDADES` (`id_cidade`),
KEY `FK_EMPRESAS_ESTADOS` (`id_estado`),
KEY `FK_EMPRESAS_EMPRESASMATRIZ` (`id_grupo`),
KEY `FK_EMPRESAS_FUNCIONALIDADES` (`id_funcionalidade`),
CONSTRAINT `FK_EMPRESAS_CIDADES` FOREIGN KEY (`id_cidade`) REFERENCES `cidades` (`id`),
CONSTRAINT `FK_EMPRESAS_EMPRESASMATRIZ` FOREIGN KEY (`id_grupo`) REFERENCES `emp_grupo` (`id`),
CONSTRAINT `FK_EMPRESAS_ESTADOS` FOREIGN KEY (`id_estado`) REFERENCES `estados` (`id`),
CONSTRAINT `FK_EMPRESAS_FUNCIONALIDADES` FOREIGN KEY (`id_funcionalidade`) REFERENCES `emp_funcionalidades` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=54 DEFAULT CHARSET=utf8

Alter table foreign key constraint fails

When I try to do this:
ALTER TABLE credit_card ADD CONSTRAINT fk_company FOREIGN KEY (company_id) REFERENCES company (id);
I got the error a foreign key constraint fails, but I don't understand why. The company_id column has same type of company.id column as you can see:
Company table
CREATE TABLE `company` (
`id` bigint NOT NULL AUTO_INCREMENT,
`code` varchar(10) NOT NULL,
`description` varchar(50) NOT NULL,
`currency_id` bigint NOT NULL,
`language_id` bigint DEFAULT NULL,
`address_id` bigint DEFAULT NULL,
`creation_time` datetime NOT NULL,
`modification_time` datetime DEFAULT NULL,
`deleted` tinyint(1) NOT NULL DEFAULT '0',
`cost_center_modifiable` tinyint(1) DEFAULT NULL,
`use_colleague_cost_center` tinyint(1) DEFAULT NULL,
`fixed_guest_company` varchar(50) DEFAULT NULL,
`info_number` int DEFAULT NULL,
`use_kilometric_rate` tinyint(1) DEFAULT NULL,
`use_multiple_km_rate` tinyint(1) DEFAULT NULL,
`email_required` tinyint(1) DEFAULT NULL,
`logo` varchar(255) DEFAULT NULL,
`holding_id` bigint NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `code` (`code`),
KEY `fk_company_address1` (`address_id`),
KEY `fk_company_currency1` (`currency_id`),
KEY `company_language_FK` (`language_id`),
KEY `company_holding_FK` (`holding_id`),
CONSTRAINT `company_currency_FK` FOREIGN KEY (`currency_id`) REFERENCES `currency` (`id`),
CONSTRAINT `company_holding_FK` FOREIGN KEY (`holding_id`) REFERENCES `holding` (`id`),
CONSTRAINT `company_language_FK` FOREIGN KEY (`language_id`) REFERENCES `language` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=142 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
Credit_card table
CREATE TABLE `credit_card` (
`id` bigint NOT NULL AUTO_INCREMENT,
`username` varchar(50) DEFAULT NULL,
`pan` varchar(16) NOT NULL,
`account` varchar(50) DEFAULT NULL,
`begin_date` date NOT NULL,
`end_date` date NOT NULL,
`disabled` tinyint(1) NOT NULL DEFAULT '0',
`creation_time` datetime NOT NULL,
`modification_time` datetime DEFAULT NULL,
`company_id` bigint NOT NULL,
PRIMARY KEY (`id`),
KEY `username` (`username`),
KEY `pan` (`pan`),
CONSTRAINT `fk_credit_card_user_ext` FOREIGN KEY (`username`) REFERENCES `users_extension` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=64 DEFAULT CHARSET=utf8mb3
Dont make auto increment columns as foreign keys or unless not sure, dont reference these to autoincrement columns as it may end up making the table with foreign key issue a constraint violation if redundant entries are expected to be made in either of the tables.
Might be the case the related data is already ingested and then the table is altered

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)

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?