Home  >  Q&A  >  body text

mysql: key reference and table reference do not match

error message:

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 List:

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:

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 created a FAQ table to combine with the products table, but it keeps getting errors and I can't find where the questions in the table go wrong. Thanks for the help.

P粉798010441P粉798010441459 days ago612

reply all(1)I'll reply

  • P粉845862826

    P粉8458628262023-07-19 00:36:01

    Remove the comma in this English paragraph - PRIMARY KEY (id, version_id), remove not null in product_id BINARY(16), remove version_id. REFERENCES product (id,version_id)

    https://dbfiddle.uk/rg25idw-

    In the referenced table, there must be an index in which the referenced columns are in the same order as the first column.


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

    reply
    0
  • Cancelreply