mysql - Allow a foreign key insertion only if another foreign key is matched -


i have these 3 tables:

--company-- company_id (primary key) name  --location-- location_id (primary key) company_id (foreign key referencing company.company_id)    name  --asset-- asset_id (primary_key) company_id (foreign key referencing company.company_id)   location_id (foreign key referencing location.location_id) name 

i enforce this: location_id asset acceptable if asset.company_id = location.company_id

currently i'm enforcing through application, wondering if it's possible using mysql.

drop table company; create table company (   company_id int not null auto_increment,     name varchar(100) not null, primary key(company_id) )engine=innodb ;  insert company(name) values ('acme widgets'); insert company(name) values ('goober chocolates'); insert company(name) values ('fat r us');   drop table location; create table location (   location_id int not null,     company_id int not null,     name varchar(100) not null, primary key(company_id,location_id), foreign key (company_id ) references company(company_id) )engine=innodb ;  insert location(location_id,company_id,name) values (1,1,'cambridge ma'); insert location(location_id,company_id,name) values (1,2,'boston ma'); insert location(location_id,company_id,name) values (1,3,'topeka ks'); insert location(location_id,company_id,name) values (2,1,'everywhere usa'); insert location(location_id,company_id,name) values (2,666,'fail test fail');  create table asset (   asset_id int not null auto_increment,     company_id int not null,     location_id int not null,     name varchar(100) not null,     primary key(asset_id),     constraint fk_asset_cl foreign key (company_id,location_id)                         references location(company_id,location_id) )engine=innodb ;  insert asset(company_id,location_id,name) values (1,1,'typewriter'); insert asset(company_id,location_id,name) values (1,8,'typewriter fail'); 

remember fk must single parent table key in same composite order (company,location) in example

insert asset(company_id,location_id,name) values (1,8,'typewriter fail'); error 1452 (23000): cannot add or update child row: foreign key constraint fails ... 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -