Mysql generating error creating Foreign key: Error Code: 1215 Cannot add Foreign key Constraint

Asked

Viewed 56 times

1

mysql is returning this error to me every time I try to add Foreign key to these tables, but I already checked the types of both fields and everything is the same.

The table where I have the primary key I’m trying to reference in the other table.

CREATE TABLE `clients` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `internal_client_id` bigint(20) unsigned NOT NULL,
  `codigo` int(10) unsigned NOT NULL,
  `razao_social` varchar(150) COLLATE utf8mb4_unicode_ci NOT NULL,
  `cnpj` varchar(150) COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `clients_codigo_unique` (`codigo`),
  UNIQUE KEY `clients_razao_social_unique` (`razao_social`),
  UNIQUE KEY `clients_cnpj_unique` (`cnpj`),
  KEY `clients_internal_client_id_foreign` (`internal_client_id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

The table containing the Foreign key

CREATE TABLE payrolls ( 
  importing_user_id BIGINT(20) UNSIGNED NOT NULL, 
  file_name VARCHAR(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL, 
  file_id VARCHAR(35) COLLATE utf8mb4_unicode_ci DEFAULT NULL, 
  event_id BIGINT(20) UNSIGNED NOT NULL, 
  VALUE DECIMAL(12,2) DEFAULT NULL, 
  YEAR VARCHAR(4) COLLATE utf8mb4_unicode_ci DEFAULT NULL, 
  MONTH VARCHAR(2) COLLATE utf8mb4_unicode_ci DEFAULT NULL, 
  user_id BIGINT(20) UNSIGNED NOT NULL, 
  client_id BIGINT(20) UNSIGNED NOT NULL, 
  id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  created_at TIMESTAMP NULL DEFAULT NULL, 
  updated_at TIMESTAMP NULL DEFAULT NULL, PRIMARY KEY (id)
);

I’ve tried these ways:

ALTER TABLE payrolls ADD 
FOREIGN KEY (client_id) REFERENCES clients(id);
ALTER TABLE `payrolls` ADD CONSTRAINT `fk_clients` FOREIGN KEY ( `client_id` ) REFERENCES `clients` ( `id` ) ;
  • See the manual for the correct syntax to declare a Foreign key.

  • @anonymity I have seen my king.

  • Check that the Engines are equal -> show create table tableName

  • The entity payrolls has any record? If you have, check if there is any reference in client_id to any record that is not present in the entity clients.

  • You are using the engine Myisam that does not support foreign keys.

  • @Marcosxavier , it was just that! Wrong engine!

  • @Augustovasques was right, thank you!

Show 2 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.