I am trying to create a series of tables with multiple foreign key relationships. The first of the two tables have a two-column primary key, once specified by us and the other specified by the manufacturer. The error is occurring when the third query is attempted. I’m not really sure what is going wrong here so any help would be sincerely appreciated.
SQL
CREATE TABLE rugs (
id INTEGER NOT NULL AUTO_INCREMENT,
manufacturer_id INTEGER NOT NULL,
name VARCHAR(255),
description TEXT,
PRIMARY KEY (id, manufacturer_id)
);
CREATE TABLE carpets (
id INTEGER NOT NULL AUTO_INCREMENT,
manufacturer_id INTEGER NOT NULL,
name VARCHAR(255),
warranty TEXT,
description TEXT,
fiber_name VARCHAR(255),
brand_name VARCHAR(255),
texture_name VARCHAR(255),
PRIMARY KEY (id, manufacturer_id)
);
CREATE TABLE carpet_styles (
id INTEGER NOT NULL AUTO_INCREMENT,
carpet_id INTEGER,
style_name VARCHAR(255),
PRIMARY KEY (id),
FOREIGN KEY (carpet_id) REFERENCES carpets (manufacturer_id)
);
CREATE TABLE carpet_colors (
id INTEGER NOT NULL AUTO_INCREMENT,
carpet_id INTEGER,
color_name VARCHAR(255),
color_category VARCHAR(255),
PRIMARY KEY (id),
FOREIGN KEY (carpet_id) REFERENCES carpets (manufacturer_id)
);
CREATE TABLE carpet_custom_names (
id INTEGER NOT NULL AUTO_INCREMENT,
carpet_id INTEGER,
custom_name VARCHAR(255),
PRIMARY KEY (id),
FOREIGN KEY (carpet_id) REFERENCES carpets (manufacturer_id)
);
CREATE TABLE rug_styles (
id INTEGER NOT NULL AUTO_INCREMENT,
rug_id INTEGER,
style_name VARCHAR(255),
PRIMARY KEY (id),
FOREIGN KEY (rug_id) REFERENCES rugs (manufacturer_id)
);
CREATE TABLE rug_colors (
id INTEGER NOT NULL AUTO_INCREMENT,
rug_id INTEGER,
color_name VARCHAR(255),
color_category VARCHAR(255),
PRIMARY KEY (id),
FOREIGN KEY (rug_id) REFERENCES rugs (manufacturer_id)
);
CREATE TABLE rug_shapes (
id INTEGER NOT NULL AUTO_INCREMENT,
rug_id INTEGER,
shape_name VARCHAR(255),
shape_category VARCHAR(255),
PRIMARY KEY (id),
FOREIGN KEY (rug_id) REFERENCES rugs (manufacturer_id)
);
CREATE TABLE catalog_contents (
id INTEGER NOT NULL AUTO_INCREMENT,
catalog_id INTEGER,
carpet_id INTEGER,
rug_id INTEGER,
PRIMARY KEY (id),
FOREIGN KEY (rug_id) REFERENCES rugs (id),
FOREIGN KEY (carpet_id) REFERENCES carpets (id),
FOREIGN KEY (catalog_id) REFERENCES catalogs (id)
);
This appears to be due to the fact that although
carpets.manufacturer_idis part of a composite key, it has no index of its own. You must create an index on it separately from the compositePRIMARY KEY. The same is true forrugs.manufacturer_id