【问题标题】:Mysql composite key order relevancemysql复合键顺序相关性
【发布时间】:2014-06-16 01:06:49
【问题描述】:

我有这个 mySql 表:

create table associations
(email1 varchar(30), 
email2 varchar(30),
primary key(email1, email2));

如果我按如下方式插入两行,则现在在此表中:

insert into associations values('a@abc.com','b@abc.com');

insert into associations values('b@abc.com','a@abc.com');

这些在数据库中是可以接受的。我想要做的是它们不应该被数据库接受,因为我只对键的组合感兴趣,而不是它们的顺序

mysql(或任何其他数据库)中是否有任何内置功能/关键字/hack 允许我这样做?

【问题讨论】:

  • 不可能作为复合主键,但您可以创建功能索引。我不认为 MySQL 支持这一点。另一种解决方案可能是添加约束email1 <= email2

标签: mysql database key composite


【解决方案1】:

这对我有用,我想出了这个触发器:

mysql> create trigger insert_check_associations before insert on associations
-> for each row
-> begin
-> if new.email1>new.email2 then
-> set @a = new.email2;
-> set new.email2 = new.email1;
-> set new.email1 = @a;
-> end if;
-> end;//

查询正常,0 行受影响(0.07 秒)

此触发器按升序交换两个值。

【讨论】:

    【解决方案2】:

    在支持检查约束的 RDBMS 中,您可能会强制这两个条目以特定顺序出现。* 这可以确保不会发生您描述的那种重复,因为两个顺序之一将被拒绝。不幸的是,MySQL 不提供检查约束,尽管对this question 的公认答案提出了一种使用触发器实现类似结果的方法。

    * 这是假设您对列数据类型有一个总顺序,在这种情况下您就是这样做的。

    【讨论】:

      猜你喜欢
      • 2014-12-03
      • 1970-01-01
      • 2019-01-10
      • 2011-11-05
      • 1970-01-01
      • 1970-01-01
      • 2017-10-29
      • 2023-04-06
      • 1970-01-01
      相关资源
      最近更新 更多