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
Related
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;
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
I am trying to add 2 Tables to my database using these 2 queries, but I get this error on adding OnetoOne relationship, I am using shopware as framework to execute this queries.
The error says :
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key
constraint"
CREATE TABLE `texdata_productFields` (
`id` BINARY(16) NOT NULL,
`product_id` BINARY(16) NOT NULL,
`product_version_id` BINARY(16) NOT NULL,
`form_number` INT(11) NOT NULL,
`quality_number` INT(11) NOT NULL,
`color_number` INT(11) NOT NULL,
`color_group` INT(11) NULL,
`variant_number` INT(11) NOT NULL,
`size_value` VARCHAR(255) NOT NULL,
`size_format` VARCHAR(255) NULL,
`color_rgb_code` VARCHAR(255) NULL,
`color_group_rgb_code` VARCHAR(255) NULL,
`main_article_number` VARCHAR(255) NULL,
`care_symbols` VARCHAR(255) NULL,
`created_at` DATETIME(3) NOT NULL,
`updated_at` DATETIME(3) NULL,
PRIMARY KEY (`id`),
CONSTRAINT `json.texdata_productFields.translated` CHECK (JSON_VALID(`translated`))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `texdata_productFields_translation` (
`materials` VARCHAR(255) NULL,
`colorGroupName` VARCHAR(255) NULL,
`variantDescription` VARCHAR(255) NULL,
`freiText1` VARCHAR(255) NULL,
`freiText2` VARCHAR(255) NULL,
`freiText3` VARCHAR(255) NULL,
`created_at` DATETIME(3) NOT NULL,
`updated_at` DATETIME(3) NULL,
`texdata_productFields_id` BINARY(16) NOT NULL,
`language_id` BINARY(16) NOT NULL,
PRIMARY KEY (`texdata_productFields_id`,`language_id`),
KEY `fk.texdata_productFields_translation.texdata_productFields_id` (`texdata_productFields_id`),
KEY `fk.texdata_productFields_translation.language_id` (`language_id`),
CONSTRAINT `fk.texdata_productFields_translation.texdata_productFields_id` FOREIGN KEY (`texdata_productFields_id`) REFERENCES `texdata_productFields` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk.texdata_productFields_translation.language_id` FOREIGN KEY (`language_id`) REFERENCES `language` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Language Table is a default table, this is the query that builds it:
CREATE TABLE `language` (
`id` BINARY(16) NOT NULL,
`parent_id` BINARY(16) NULL,
`locale_id` BINARY(16) NOT NULL,
`translation_code_id` BINARY(16) NULL,
`name` VARCHAR(255) NOT NULL,
`custom_fields` JSON NULL,
`created_at` DATETIME(3) NOT NULL,
`updated_at` DATETIME(3) NULL,
PRIMARY KEY (`id`),
CONSTRAINT `json.language.custom_fields` CHECK (JSON_VALID(`custom_fields`)),
KEY `fk.language.parent_id` (`parent_id`),
KEY `fk.language.locale_id` (`locale_id`),
KEY `fk.language.translation_code_id` (`translation_code_id`),
CONSTRAINT `fk.language.parent_id` FOREIGN KEY (`parent_id`) REFERENCES `language` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk.language.locale_id` FOREIGN KEY (`locale_id`) REFERENCES `locale` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk.language.translation_code_id` FOREIGN KEY (`translation_code_id`) REFERENCES `locale` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
You probably need to make sure that you have set up the texdata_productFields_id and language_idcolumn in the child table to a nullable column.
If you set
ON DELETE SET NULL
To your foreign key then it won't allow you to set the field as
NOT NULL
In my MySQL query I'm getting this error:
Cannot add foreign key constraint error
What could be the reason?
CREATE TABLE `social_account` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL,
`type` enum('facebook','Twitter') DEFAULT NULL,
`pageid` varchar(200) DEFAULT NULL,
`accesstoken` varchar(200) DEFAULT NULL,
`pagename` varchar(200) DEFAULT NULL,
`ProfilePicture` varchar(200) DEFAULT NULL,
`page_url` varchar(300) DEFAULT NULL,
`accesstokensecreat` varchar(200) DEFAULT NULL,
`is_expire` int(1) DEFAULT '0',
PRIMARY KEY (`ID`),
KEY `fk_user_social_account` (`user_id`),
CONSTRAINT `fk_user_social_account` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4
may be Your Foreign key datatype is not matched with the referring table
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?