微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

mysql – MariaDB如何处理FOREIGN KEY约束中使用的ENUM类型?

紧跟这个问题,

> How does MySQL handle joins on ENUMs?

如果引用表在ENUM中的值比引用的表中的值多得多,那么MysqL如何工作?它是否仅基于全局ENUM文本键(符号)验证完整性?或者底层的整数值?

解决方法:

related question所示,枚举上的JOINS是“按价值”.另一方面,约束条件是“按位置”验证的.这种行为让我觉得反直觉.使用与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"))

所以’X’根据外键约束是有效的.正如Evan所说,JOIN表现不同:

SELECT * FROM foo JOIN bar USING(a);
Empty set (0.00 sec)

尽管如此,bar中的行由外键验证,foo和bar之间的连接为空.

最初使用ENUM作为MysqL系列中缺少CHECK CONSTRAINTS的替代品可能很诱人.然而,FOREIGN KEYS与ENUM一起工作的方式可以射击你的脚.子类型的典型模式如下:

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

因此外键验证枚举中的位置,而不是值本身.

Postgresql不允许在不同的枚举之间使用外键,因此无法在那里重现这种情况:

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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐