Question

I want to create these 3 tables in my MySQL database:

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
);

The problem is with the last table. I get an error:

1005 - Can't create table 'test1.categories_products' (errno: 150)

But when i try to create it without the constraints it works.

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

I need the constraints in case a product or a category is removed. What am i doing wrong?

Was it helpful?

Solution

There seems to be a typo

CREATE TABLE product

(singular)

and then referencing

FOREIGN KEY (product_id) REFERENCES products (product_id)

(plural).

OTHER TIPS

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
);

You created "product" but referenced "products".

By the way, you should create an ID column and use this one as primary key in "categories_products" and add a second (unique) index on both columns. This is best practice and INNODB does internally create an ID column anyway so...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top