Mysql 外键引用tableA.column或tableB.column
是否可以让外键(InnoDB)引用两个可能的表 如果没有,是否有解决方法 有两个不同的主题包含相同的字段(接口id)。第三个表引用此字段 例如:Mysql 外键引用tableA.column或tableB.column,mysql,foreign-keys,innodb,Mysql,Foreign Keys,Innodb,是否可以让外键(InnoDB)引用两个可能的表 如果没有,是否有解决方法 有两个不同的主题包含相同的字段(接口id)。第三个表引用此字段 例如: physical_interface ( id, name, etc ) virtual_interface ( id, name, etc ) usage ( interface_id, etc ) 我有一个使用视图的想法,但遇到了与SQLServer相关的问题:因此,您似乎无法在外键中使用视图 我想,另一种选择是将所有接口存储在一个表中,但我觉得
physical_interface ( id, name, etc )
virtual_interface ( id, name, etc )
usage ( interface_id, etc )
我有一个使用视图的想法,但遇到了与SQLServer相关的问题:因此,您似乎无法在外键中使用视图
我想,另一种选择是将所有接口存储在一个表中,但我觉得这样做的组织性较差。嗯,答案很有趣。MySQL 5.6.14,我的版本,不会阻止你创建一个与2个表的外键关系,但这是一个坏主意。让我告诉你为什么 创建两个主表:test1和test3
create table test1 (field1 int, primary key (field1));
create table test3 (field1 int, primary key (field1));
创建与两个表的字段1具有FK关系的从属表
create table test2 (
field0 int,
field1 int,
constraint fk_test2_test1
foreign key (field1)
references test1 (field1),
constraint fk_test2_test3
foreign key (field1)
references test3 (field1)
);
太好了。现在,让我们添加一些数据并查看问题:
insert into test1 values (1);
insert into test3 values (3);
主表已完成。让我们向依赖表添加数据
insert into test2 values (100, 1);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`test`.`test2`, CONSTRAINT `fk_test2_test3` FOREIGN KEY (`field1`) REFERENCES `test3` (`field1`))
insert into test2 values (100, 3);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`test`.`test2`, CONSTRAINT `fk_test2_test1` FOREIGN KEY (`field1`) REFERENCES `test1` (`field1`))
insert into test2 values (100, 2);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`test`.`test2`, CONSTRAINT `fk_test2_test1` FOREIGN KEY (`field1`) REFERENCES `test1` (`field1`))
所以…不要那样做
提案
create table interface_type (
id int auto_increment,
type_name varchar(30),
primary key (id)
);
create table interface (
id int auto_increment,
interface_name varchar(30),
interface_type int,
primary key (id),
constraint fk_interface_type
foreign key (interface_type)
references interface_type (id)
);
create table `usage` (
id int auto_increment,
interface_id int,
primary key (id),
constraint fk_usage_interface
foreign key (interface_id)
references interface (id)
);
现在,您可以在interface\u type
表中添加多种类型的接口,例如:
insert into interface_type (type_name) values ('physical'), ('virtual');
然后,在接口
表中添加所需数量的接口,并根据需要在用法
表中引用它们