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

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

Related

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

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

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

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

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row on CONSTRAINT `fk_users_has_ratings_businesses1

I'm getting this error when i try to insert new ratings
Error: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`yuldi`.`users_ratings`, CONSTRAINT `fk_users_has_ratings_businesses1` FOREIGN KEY (`business_id`) REFERENCES `businesses` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)
below database table structure with some foreign keys. i'm confused with adding multiple primary and foreign keys. please help me to sort out this issue
CREATE TABLE IF NOT EXISTS `yuldi`.`businesses` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`state` VARCHAR(100) NOT NULL,
`slug` VARCHAR(250) NOT NULL,
`city` VARCHAR(100) NOT NULL,
`suburb` VARCHAR(100) NOT NULL,
`business_name` VARCHAR(100) NOT NULL,
`business_address` VARCHAR(250) NOT NULL,
`business_postal` VARCHAR(10) NOT NULL,
`business_postal_id` INT(11) NOT NULL,
`business_phone` VARCHAR(50) NOT NULL,
`business_phone1` VARCHAR(50) NOT NULL,
`business_phone2` VARCHAR(50) NOT NULL,
`business_email` VARCHAR(100) NOT NULL,
`business_website` VARCHAR(200) NOT NULL,
`business_details` VARCHAR(5000) NOT NULL,
`business_openinghours` VARCHAR(200) NOT NULL,
`business_service` VARCHAR(200) NOT NULL,
`business_addtionalinfo` VARCHAR(200) NOT NULL,
`business_lat` FLOAT(10,6) NOT NULL,
`business_lng` FLOAT(10,6) NOT NULL,
`identity` VARCHAR(100) NOT NULL,
`status` INT(11) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB
AUTO_INCREMENT = 232
DEFAULT CHARACTER SET = utf8;
CREATE TABLE IF NOT EXISTS `yuldi`.`ratings` (
`id` VARCHAR(36) NOT NULL,
`model` VARCHAR(255) NOT NULL,
`value` FLOAT(8,4) NULL DEFAULT '0.0000',
`comment` TEXT NULL DEFAULT NULL,
`created` DATETIME NULL DEFAULT NULL,
`modified` DATETIME NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `UNIQUE_RATING` (`model` ASC))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
CREATE TABLE IF NOT EXISTS `yuldi`.`users` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`user_email` VARCHAR(255) NULL DEFAULT NULL,
`user_password` CHAR(100) NULL DEFAULT NULL,
`user_name` VARCHAR(255) NULL DEFAULT NULL,
`user_code` VARCHAR(255) NULL DEFAULT NULL,
`user_status` TINYINT(4) NULL DEFAULT '0',
`created` DATETIME NULL DEFAULT NULL,
`modified` DATETIME NULL DEFAULT NULL,
`ip_address` VARCHAR(15) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB
AUTO_INCREMENT = 14
DEFAULT CHARACTER SET = utf8;
CREATE TABLE IF NOT EXISTS `yuldi`.`users_ratings` (
`user_id` INT(11) NOT NULL,
`rating_id` VARCHAR(36) NOT NULL,
`business_id` INT(11) NOT NULL,
PRIMARY KEY (`user_id`, `rating_id`, `business_id`),
INDEX `fk_users_has_ratings_ratings1_idx` (`rating_id` ASC),
INDEX `fk_users_has_ratings_users1_idx` (`user_id` ASC),
INDEX `fk_users_has_ratings_businesses1_idx` (`business_id` ASC),
CONSTRAINT `fk_users_has_ratings_businesses1`
FOREIGN KEY (`business_id`)
REFERENCES `yuldi`.`businesses` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_users_has_ratings_ratings1`
FOREIGN KEY (`rating_id`)
REFERENCES `yuldi`.`ratings` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_users_has_ratings_users1`
FOREIGN KEY (`user_id`)
REFERENCES `yuldi`.`users` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
The problem is coming from this:
CONSTRAINT `fk_users_has_ratings_businesses1`
FOREIGN KEY (`business_id`)
REFERENCES `yuldi`.`businesses` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
The record you're trying to insert / update - probably user_ratings - is foreign keyed to the businesses table; you can't create a user_ratings record without a business_id, and that business_id must actually exist as an id in the businesses table.

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?