Mysql table 多主键关系

Mysql table multiple primary key relation

我有 table 两列。 ID1 和 ID2。 我想将 2 列作为主键。

当插入ID1=22 , ID2=55ID1=55 , ID2=22时,这个是一样的,不插入显示错误!

注意*:这个table是一个关系。同为兄妹。真的有3个列: ID1 , ID2 , TYP.

  1. ID1 = 第一个用户id
  2. ID2 = 第二个用户id
  3. TYP = 关系类型(bro/sis/uncle/aunt...)

现在如何将所有列设置为主列?当 ID1 和 ID2 像我上面解释的那样并且也将 TYP 设为主要时?谢谢@>

您可以像 this or in this 示例中那样拥有多列主键。 只需将 PRIMARY KEY (ID1, ID2) 添加到您的 create table 语句即可。

我有点担心的是你说 (22/55)(55/22) 应该被检测为重复项。仅在 ID1 和 ID2 上使用 PK 就不会出现这种情况。 (22/55)(55/22) 是不同的,但是对于 table 关系完全没问题:如果 22 是 55 的姨妈,那么 55 是 侄子 的 22,因此 应该 在 table.

中有两行

MySQL 没有一种简单的方法来识别 (id1, id2) 和 (id2, id1) 应该相同。

因此,您需要创建一个触发器来处理此问题。如果 (id1, id2) 已经是主键或唯一键,则如下所示:

delimiter $$
create trigger tr_table_insert before insert on t
for each row 
begin
    if (exists (select 1
                from t
                where t.id2 = new.id1 and t.id1 = new.id2
               )
       ) then
        set msg = concat('Combination ', new.id1, ' and ', new.id2, ' already exists);
    signal sqlstate '45000' set message_text = msg;
    end if;
end;
delimiter $$;