MySQL - 无法创建表(错误号:150) - 外键约束

时间:2014-02-22 14:54:33

标签: mysql constraints cascade

我想在MySQL数据库中创建这三个表:

CREATE TABLE categories (
    category_id SMALLINT NOT NULL AUTO_INCREMENT,
    category VARCHAR(255) NOT NULL UNIQUE,
    description TINYTEXT NOT NULL,
    PRIMARY KEY (category_id)
);


CREATE TABLE product (
    product_id SMALLINT NOT NULL AUTO_INCREMENT,
    product VARCHAR(255) NOT NULL UNIQUE,
    description TINYTEXT NOT NULL,
    price DECIMAL(6,2) NOT NULL,
    PRIMARY KEY (product_id)
);

CREATE TABLE categories_products (
    category_id SMALLINT NOT NULL,
    product_id SMALLINT NOT NULL,
    PRIMARY KEY (category_id, product_id),
    FOREIGN KEY (category_id) REFERENCES categories (category_id)
        ON DELETE CASCADE ON UPDATE CASCADE,
    FOREIGN KEY (product_id) REFERENCES products (product_id)
        ON DELETE CASCADE ON UPDATE CASCADE
);

问题在于最后一张表。我收到一个错误:

  

1005 - 无法创建表'test1.categories_products'(错误号码:   150)

但是当我尝试在没有约束的情况下创建它时,它会起作用。

CREATE TABLE categories_products (
    category_id SMALLINT NOT NULL,
    product_id SMALLINT NOT NULL,
    PRIMARY KEY (category_id, product_id)
);

如果删除了产品或类别,我需要约束。我做错了什么?

2 个答案:

答案 0 :(得分:2)

CREATE TABLE categories (
    category_id SMALLINT NOT NULL AUTO_INCREMENT,
    category VARCHAR(255) NOT NULL UNIQUE,
    description TINYTEXT NOT NULL,
    PRIMARY KEY (category_id)
);


CREATE TABLE products (
    product_id SMALLINT NOT NULL AUTO_INCREMENT,
    product VARCHAR(255) NOT NULL UNIQUE,
    description TINYTEXT NOT NULL,
    price DECIMAL(6,2) NOT NULL,
    PRIMARY KEY (product_id)
);

CREATE TABLE categories_products (
    category_id SMALLINT NOT NULL,
    product_id SMALLINT NOT NULL,
    PRIMARY KEY (category_id, product_id),
    FOREIGN KEY (category_id) REFERENCES categories (category_id)
        ON DELETE CASCADE ON UPDATE CASCADE,
    FOREIGN KEY (product_id) REFERENCES products (product_id)
        ON DELETE CASCADE ON UPDATE CASCADE
);

您创建了“产品”,但引用了“产品”。

顺便说一句,您应该创建一个ID列并将其用作“categories_products”中的主键,并在两列上添加第二个(唯一)索引。这是最佳实践,INNODB无论如何都会在内部创建ID列......

答案 1 :(得分:2)

似乎有一个错字

CREATE TABLE product

(单数)

然后引用

FOREIGN KEY (product_id) REFERENCES products (product_id)

(复数)。