gpt4 book ai didi

mysql - 制作复合键 "bidirectional"

转载 作者:行者123 更新时间:2023-11-29 01:41:49 26 4
gpt4 key购买 nike

我有一个表,我在其中使用复合键作为主键。它创建了类似的东西:

CREATE TABLE FOO(
BAR1 INT,
BAR2 INT,
PRIMARY KEY (BAR1, BAR2))

BAR1 和 BAR2 是其他表的 FK:s,我想确保我的 FOO 表中始终有零个或一个元组,其中这两个键同时存在。基本上我希望它同时是这样的:

PRIMARY KEY (BAR2, BAR1)

同时,必须允许这两个 key 与其他 key 配对任意次数,这样它们中的每一个都不能是唯一的。

所以当我完成后

INSERT INTO FOO VALUES (1,2); 

架构不允许

INSERT INTO FOO VALUES (2,1);

在mysql中有什么好的方法可以解决这个问题?

最佳答案

一个可能的解决方案是使用触发器。

create trigger bi_foo before insert on foo
for each row
begin
if exists(select 1 from foo where bar1 = NEW.bar2 and bar2 = NEW.bar1)
then
signal sqlstate '50000' set message_text="Oops";
end if;
end

这会起作用:

insert into foo values (1, 2), (3, 4), (5, 6);
insert into foo values (3, 2), (3, 5), (1, 6);

这会失败:

mysql> insert into foo values (2, 1);
ERROR 1644 (50000): Oops

关于mysql - 制作复合键 "bidirectional",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19039344/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com