【问题标题】:Allow a foreign key insertion only if another foreign key is matched仅当匹配另一个外键时才允许插入外键
【发布时间】:2013-05-14 13:03:13
【问题描述】:

我有这 3 张桌子:

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

我想强制执行:仅当 assets.company_id = location.company_id 时,资产的 location_id 才可接受

目前我正在通过应用程序执行此操作,我想知道是否可以仅使用 MySQL 来执行此操作。

【问题讨论】:

  • 你尝试了什么?
  • 我可能弄错了,但我认为 MySQL 中实际上并没有强制执行外键。
  • 目前我正在通过应用程序逻辑执行此操作,我想仅使用 mysql 执行此操作
  • 你用的是哪个引擎?
  • @JonathonReinhart 一些 MySQL 引擎不支持它。 InnoDB 引擎可以。

标签: mysql database-design foreign-keys database-schema


【解决方案1】:
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 into company(name) values ('acme widgets');
insert into company(name) values ('goober chocolates');
insert into 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 into location(location_id,company_id,name) values (1,1,'Cambridge MA');
insert into location(location_id,company_id,name) values (1,2,'Boston MA');
insert into location(location_id,company_id,name) values (1,3,'Topeka KS');
insert into location(location_id,company_id,name) values (2,1,'Everywhere USA');
insert into location(location_id,company_id,name) values (2,666,'Fail Test this will 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 into asset(company_id,location_id,name) values (1,1,'typewriter');
insert into asset(company_id,location_id,name) values (1,8,'typewriter fail');

请记住,在此示例中,您的 FK 必须返回到具有相同复合顺序(公司、位置)的键的单个父表

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

【讨论】:

  • 我知道 location 的主键可能应该是 location_id 然后在 (company_id,location_id) 上添加另一个 CREATE INDEX stmt 以便资产可以将其用于其 FK,但这只是一小步说明它有效的事实
猜你喜欢
  • 2016-07-15
  • 1970-01-01
  • 1970-01-01
  • 2013-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
相关资源
最近更新 更多