【问题标题】:In SQL can you enforce unicity of undirected edge using sum and product computed columns? [duplicate]在 SQL 中,您可以使用 sum 和 product 计算列来强制实现无向边的唯一性吗? [复制]
【发布时间】:2021-04-11 16:28:21
【问题描述】:
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),
  s = id_from + id_to persistent,
  p = id_from * id_to persistent,
  unique(s, p),
  name varchar(100) unique,
);

这是为每对位置强制执行单程(进或回)的正确方法吗?

【问题讨论】:

  • 该问题是对您所指问题的补充
  • 这是对该问题的潜在答案,而不是新问题。使用此方法发布自我答案
  • 一个二次方程最多有两个解。它至少有 id_from 和 id_to。所以方程 xx - sx + p=0 总是正好有 2 个解,即 id_from 和 id_to。
  • 关于数学上是否保证只有一对 x,y 对 x + y = s 和 x*y = p 的问题是数学问题而不是编程问题。您在数学上链接的问题已经通过将其表示为二次方程来说明这一点。如果您对数学元素有其他问题,您应该在那里提问。一旦确认,这只是重复问题的答案

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


【解决方案1】:

没有。如果您想要不考虑方向的唯一边缘,请使用最小值和最大值:

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),
  id_least as (case when id_from < id_to then id_from else id_to end) persistent,
  id_greatest as (case when id_from < id_to then id_to else id_from end) persistent,
  unique(least_id, greatest_id),
  name varchar(100) unique,
);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多