Eva*_*oll 3 mysql mariadb foreign-key enum
紧接着这个问题,
如果引用表中的值ENUM比被引用表的值多或少,MySQL 如何工作?它是否仅基于全局ENUM文本密钥(符号)来验证完整性?还是底层的整数值?
如相关问题所示,JOINS onenums是“按值”。另一方面,约束是“按位置”验证的。这种行为让我觉得很违反直觉。使用与 Evan 类似的设置:
CREATE TABLE foo ( a ENUM ('A', 'B') not null primary key );
CREATE TABLE bar ( a ENUM ('X', 'Y', 'Z') not null primary key );
ALTER TABLE bar ADD CONSTRAINT fk_foo_bar
FOREIGN KEY (a) REFERENCES foo (a);
insert into foo (a) values ('A'),('B');
insert into bar (a) values ('X'); -- OK
insert into bar (a) values ('Z');
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails ("test3"."bar", CONSTRAINT "fk_foo_bar" FOREIGN KEY ("a") REFERENCES "foo" ("a"))
Run Code Online (Sandbox Code Playgroud)
所以根据外键约束,'X' 是有效的。正如 Evan 所展示的,JOIN 的行为不同:
SELECT * FROM foo JOIN bar USING(a);
Empty set (0.00 sec)
Run Code Online (Sandbox Code Playgroud)
因此,尽管如此,输入的行bar是由外键验证的,foo 和 bar 之间的连接是空的。
起初可能很想用它来ENUM代替CHECK CONSTRAINTSMySQL 家族中的缺失。然而,FOREIGN KEYS一起工作的方式ENUMs可能会射中你的脚。子类型的典型模式如下所示:
CREATE TABLE P
( p int not null primary key
, sub_type ENUM ('A','B')
, constraint AK_P unique (p, sub_type));
CREATE TABLE A
( p int not null primary key
, sub_type ENUM ('A')
, constraint aaa foreign key (p, sub_type)
references P (p, sub_type));
CREATE TABLE B
( p int not null primary key
, sub_type ENUM ('B')
, constraint bbb foreign key (p, sub_type)
references P (p, sub_type));
insert into P (p,sub_type) values (1,'A'),(2,'B');
insert into A (p,sub_type) values (1,'A'); -- OK
insert into B (p,sub_type) values (1,'B'); -- OK, but should not be allowed since 1 is sub_type 'A' in parent
insert into B (p,sub_type) values (2,'B'); -- Fails, but should be OK
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails ("test3"."B", CONSTRAINT "bbb" FOREIGN KEY ("p", "sub_type") REFERENCES "P" ("p", "sub_type"))
Run Code Online (Sandbox Code Playgroud)
所以外键验证枚举中的位置,而不是值本身。
PostgreSQL 不允许不同 enum 之间的外键,所以那里的情况是不可能重现的:
CREATE type e1 as ENUM ('A', 'B');
CREATE type e2 as ENUM ('X', 'Y', 'Z');
CREATE TABLE foo ( a e1 not null primary key );
CREATE TABLE bar ( a e2 not null primary key );
ALTER TABLE bar ADD CONSTRAINT fk_foo_bar
FOREIGN KEY (a) REFERENCES foo (a);
ERROR: foreign key constraint "fk_foo_bar" cannot be implemented
DETAIL: Key columns "a" and "a" are of incompatible types: e2 and e1.
Run Code Online (Sandbox Code Playgroud)