I am having trouble setting multiple foreign keys in my house-letting database.
A house has many rooms, which has many tenancies, each with a tenant. A tenant can have many tenancies.
My database is created as follows:
DROP TABLE IF EXISTS house;
CREATE TABLE house
(
house_name varchar(30) NOT NULL PRIMARY KEY,
address_first_line varchar(60),
address_city varchar(30),
address_postcode varchar(8)
);
-- rooms
DROP TABLE IF EXISTS room;
CREATE TABLE room
(
house_name varchar(30) NOT NULL,
room_number smallint NOT NULL,
PRIMARY KEY(house_name,room_number),
FOREIGN KEY (house_name) REFERENCES house(house_name)
);
-- tenants
DROP TABLE IF EXISTS tenant;
CREATE TABLE tenant
(
tenant_id smallint NOT NULL,
tenant_firstname varchar(20),
tenant_surname varchar(20),
tenant_telephone varchar(12)
);
-- rentals
DROP TABLE IF EXISTS tenancy;
CREATE TABLE tenancy
(
house_name varchar(30) NOT NULL,
room_number smallint NOT NULL,
start_date date NOT NULL,
end_date date,
tenant_id smallint NOT NULL,
advance smallint,
deposit smallint,
PRIMARY KEY (house_name,room_number,start_date),
FOREIGN KEY (house_name,room_number) REFERENCES room(house_name,room_number),
FOREIGN KEY (tenant_id) REFERENCES tenant(tenant_id)
);
This line is generating a “1005 error: Can’t create table tenancy (errno: 150)”:
FOREIGN KEY (tenant_id) REFERENCES tenant(tenant_id)
The tenancy table is a relationship between tenant and room, which is why it references both tables.
I suspect it is something really simple, but I’m struggling to get it and would appreciate a little help.
Thanks,
Richard
The
tenants.tenant_idmust bePRIMARY KEYin order toREFERENCEit asFOREIGN KEY.