【问题标题】:Is there in SQL a way to enforce unicity of undirected edge?SQL 中是否有一种方法可以强制执行无向边的唯一性?
【发布时间】:2021-01-03 16:19:34
【问题描述】:
create table Location (
id integer primary key(1, 1),
latitude decimal(8,6),
longitude decimal(9,6),
address varchar(100),
name varchar(60) unique
);

create table Journey (
id integer primary key(1,1),
id_from integer foreign key references Location(id),
id_to integer foreign key references Location(id),
name varchar(100) unique,
unique(id_from, id_to)
);

使用此架构,您可以为一对位置创建 2 个不同的旅程,一个用于进路,一个用于返回。我想要的是为每对位置强制执行一次旅程。有哪些选项可以做到这一点?

【问题讨论】:

    标签: sql sql-server unique-constraint undirected-graph


    【解决方案1】:

    最简单的方法是强制“方向”,然后使用唯一约束:

    create table Journey (
        id integer primary key,
        id_from integer foreign key references Location(id),
        id_to integer foreign key references Location(id),
        name varchar(100) unique,
        unique(id_from, id_to),
        check (id_from < id_to)
    );
    

    但是您必须记住插入值以使用触发器来确保它们是有序的。

    否则,您可以将计算列用于最小值和最大值,然后对其使用唯一约束。

    【讨论】:

    【解决方案2】:

    您可以使用 sum 和 product 计算列来强制无向边的唯一性:

    create table Location (
      id integer primary key(1, 1),
      latitude decimal(8,6),
      longitude decimal(9,6),
      address varchar(100),
      name varchar(60) unique
    );
    create table Journey (
      id integer primary key identity(1,1),
      id_from integer foreign key references Location(id),
      id_to integer foreign key references Location(id),
      s as id_from + id_to persisted,
      p as id_from * id_to persisted,
      unique(s, p),
      name varchar(100) unique,
    );
    

    是为每对位置强制执行单程(进或回)的正确方法。一个二次方程最多有两个解。它至少有 id_from 和 id_to。所以方程 xx - sx + p=0 总是正好有 2 个解,它们是 id_from 和 id_to。你可以在那里看到数学解释https://math.stackexchange.com/questions/171407/finding-two-numbers-given-their-sum-and-their-product

    【讨论】:

    • 小心溢出。例如从,到对 46341,46342
    • 这显然是从屋顶吹来的。
    猜你喜欢
    • 1970-01-01
    • 2020-02-24
    • 2013-08-20
    • 1970-01-01
    • 2021-04-11
    • 1970-01-01
    • 2010-11-18
    • 2017-06-30
    • 1970-01-01
    相关资源
    最近更新 更多