简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM