Search code examples
sqlmysqlassociationsshopware

mysql: Key reference and table reference don't match


The error information:

SQLSTATE[42000]: Syntax error or access violation: 1239 Incorrect foreign key definition for 'fk.faq.product_id': Key reference and table reference don't match

product table:

CREATE TABLE `product` (
    `id` BINARY(16) NOT NULL,
    `version_id` BINARY(16) NOT NULL,
    `created_at` DATETIME(3) NOT NULL,
    `updated_at` DATETIME(3) NULL,
    PRIMARY KEY (`id`,`version_id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

faq table:

CREATE TABLE `faq` (
    `id` BINARY(16) NOT NULL,
    `question` VARCHAR(255) NULL,
    `answer` VARCHAR(255) NULL,
    `product_id` BINARY(16) NOT NULL,
    `created_at` DATETIME(3) NOT NULL,
    `updated_at` DATETIME(3) NULL,
    PRIMARY KEY (`id`),
    KEY `fk.faq.product_id` (`product_id`),
    CONSTRAINT `fk.faq.product_id` FOREIGN KEY (`product_id`) REFERENCES `product` (`id`,`version_id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

I made a faq table to combine with the product table, but it comes always error and I can't find what is wrong with my table? thanks for help.


Solution

  • remove comma at the end of this - PRIMARY KEY (id,version_id) , remove not null from product_id BINARY(16) , remove version_id from REFERENCES product (id,version_id)

    https://dbfiddle.uk/rg25idw-

    and read

    'in the referenced table, there must be an index where the referenced columns are the first columns in the same order'

    https://dev.mysql.com/doc/refman/8.0/en/create-table-foreign-keys.html