In my MySQL query I'm getting "Cannot add foreign key constraint error", what could be the reason? - mysql

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

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

shopware onetonone relationship error :General error: 1215 Cannot add foreign key constraint

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

Foreign Keys on two different schemas mysql

I have two tables on distinct schemas
db1.invoice
CREATE TABLE IF NOT EXISTS db1.`invoice` (
`invoice_id` int(11) NOT NULL AUTO_INCREMENT,
`qsales_sale_id` int(11) DEFAULT NULL,
`invoice_id_from_dosage_id` int(11) NOT NULL,
`number` int(11) DEFAULT NULL,
`enterprise_name` varchar(100) DEFAULT NULL,
`subsidiary_name` varchar(100) DEFAULT NULL,
`subsidiary_address` varchar(200) DEFAULT NULL,
`subsidiary_phone` varchar(40) DEFAULT NULL,
`client_name` varchar(200) DEFAULT NULL,
`nit` bigint(20) DEFAULT NULL,
`was_paid` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`invoice_id`),
KEY `fk_invoice_qsales_sale1_idx` (`qsales_sale_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=457 ;
bd2.qsale_sale
CREATE TABLE IF NOT EXISTS db2.qsales_sale (
`qsales_sale_id` int(11) NOT NULL AUTO_INCREMENT,
`qsales_order_type_id` int(11) NOT NULL,
`client_id` int(11) NOT NULL,
`total_cost` decimal(10,2) DEFAULT NULL,
`currency` varchar(45) DEFAULT NULL,
`created_at` datetime DEFAULT NULL,
`has_discount` tinyint(1) DEFAULT NULL,
`created_by` int(11) NOT NULL,
`is_wholesaler` tinyint(1) NOT NULL DEFAULT '0',
`payment_type` varchar(65) DEFAULT NULL,
PRIMARY KEY (`qsales_sale_id`),
KEY `fk_qsales_sale_qsales_order_type1_idx` (`qsales_order_type_id`),
KEY `fk_qsales_sale_client1_idx` (`client_id`),
KEY `fk_qsales_sale_employee1_idx` (`created_by`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=51 ;
then i want to add a foreign key
I try:
1.
alter table bd1.invoice
add foreign key fk_invoice_qsales_sale1(qsales_sale_id)
references db2.qsales_sale (qsales_sale_id)
on delete cascade
on update cascade;
ALTER TABLE db1.invoice
ADD CONSTRAINT fk_invoice_qsales_sale1 FOREIGN KEY (qsales_sale_id)
REFERENCES db2.qsales_sale (qsales_sale_id) ON DELETE NO ACTION ON UPDATE NO ACTION;
But i have this error:
Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails (`qfix`.`#sql-a28_5`, CONSTRAINT `#sql-a28_5_ibfk_1` FOREIGN KEY (`qsales_sale_id`) REFERENCES `qsales`.`qsales_sale` (`qsales_sale_id`) ON DELETE CASCADE ON UPDATE CASCADE)
0.625 sec

MySQL Workbench error 1452

I've trying to create a foreign key from a table to another, using the tools that MySQL Workbench provides, but all that I get is this error:
ERROR 1452: Cannot add or update a child row: a foreign key constraint fails (`mediacom`.`#sql-758_4`, CONSTRAINT `med_agente_ibfk_1` FOREIGN KEY (`id_agenzia`) REFERENCES `med_agenzia` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)
SQL Statement:
ALTER TABLE `mediacom`.`med_agente`
ADD CONSTRAINT `med_agente_ibfk_1`
FOREIGN KEY (`id_agenzia`)
REFERENCES `mediacom`.`med_agenzia` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION
The thing that confuses me the most is the line mediacom.#sql-758_4, since the real query that I use is :
ALTER TABLE `mediacom`.`med_agente`
ADD INDEX `med_agente_ibfk_1_idx` (`id_agenzia` ASC) COMMENT '';
ALTER TABLE `mediacom`.`med_agente`
ADD CONSTRAINT `med_agente_ibfk_1`
FOREIGN KEY (`id_agenzia`)
REFERENCES `mediacom`.`med_agenzia` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
The index is inserted fine but the rest is ignored, why?
This is the med_agente table
CREATE TABLE `med_agente` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nome` varchar(225) DEFAULT NULL,
`cognome` varchar(225) DEFAULT NULL,
`disabilitato` tinyint(1) DEFAULT NULL,
`mod_time` datetime DEFAULT NULL,
`mod_user` varchar(255) DEFAULT NULL,
`codmobile` decimal(13,0) DEFAULT NULL,
`codfisso` decimal(13,0) DEFAULT NULL,
`id_agenzia` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `med_agente_ibfk_1_idx` (`id_agenzia`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
And this is med_agenzia
CREATE TABLE `med_agenzia` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ragSociale` varchar(255) NOT NULL,
`descrizione` varchar(255) DEFAULT NULL,
`indirizzo` varchar(255) DEFAULT NULL,
`citta` varchar(255) DEFAULT NULL,
`CAP` int(11) DEFAULT NULL,
`provincia` varchar(255) DEFAULT NULL,
`tel` int(11) DEFAULT NULL,
`mail` varchar(255) DEFAULT NULL,
`codFiscale` varchar(255) DEFAULT NULL,
`pIVA` varchar(255) DEFAULT NULL,
`id_azsuper` int(11) DEFAULT NULL,
`disabilitato` tinyint(1) DEFAULT NULL,
`mod_time` datetime DEFAULT NULL,
`mod_user` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
where's the problem???
Before you run your query
Run this :
SET FOREIGN_KEY_CHECKS=0;
Then set it to 1
SET FOREIGN_KEY_CHECKS=1;
after you run your Alter query.