mysqlmysql-cluster

MySQL Cluster - Composite foreign key error: Missing index for constraint


I want to add composite foreign key to my MySQL Cluster table. When I try locally the statement is executed, but on cluster I get the following error:

Failed to add the foreign key constraint. Missing index for constraint... in the referenced table 'y'

This is the statement:

ALTER TABLE x
 ADD CONSTRAINT fk_x_y
 FOREIGN KEY (y_id, tenant_id) 
 REFERENCES y(id, tenant_id);

I have executed SHOW FULL COLUMNS FROM for both tables and both columns in each table are the same. Also I have index in y table on id, tenant_id. MySQL Cluster version: 8.0.25-cluster

Edit 1:

SHOW CREATE TABLE results:

Table x:

CREATE TABLE `x` (
   `id` bigint(20) NOT NULL AUTO_INCREMENT,
   `tenant_id` bigint(20) DEFAULT NULL,
   PRIMARY KEY (`id`),
   KEY `fk_y_id_tenant_id` (`tenant_id`),
   CONSTRAINT `fk_x_tenant_id` FOREIGN KEY (`tenant_id`) REFERENCES `tenant` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
 ) ENGINE=ndbcluster AUTO_INCREMENT=446 DEFAULT CHARSET=utf8;

Table y:

CREATE TABLE `reference_list` (
   `id` bigint(20) NOT NULL AUTO_INCREMENT,
   `tenant_id` bigint(20) NOT NULL,
   PRIMARY KEY (`id`),
   KEY `y_id_tenant_id` (`id`,`tenant_id`),
   KEY `fk_y_id_tenant_id` (`tenant_id`),
   CONSTRAINT `fk_y_id_tenant_id` FOREIGN KEY (`tenant_id`) REFERENCES `tenant` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
 ) ENGINE=ndbcluster AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

I am aware that tenant_id is DEFAULT NULL in one table and NOT_NULL in other, but changing both to DEFAULT NULL didn't solve the problem.


Solution

  • After running: SHOW WARNINGS; I found out I had to add UNIQUE index on id, tenant_id columns.