【问题标题】:How to prevent circular references in a linked list in Postgresql?如何防止 Postgresql 中链表中的循环引用?
【发布时间】:2021-06-28 10:17:27
【问题描述】:

表格和有效数据是这样的:

| id | after_id |
| -- | -------- |
| a  | null     |
| b  | a        |
| c  | b        |
| d  | c        |

我们的目标是防止这样的事情发生:

| id | after_id |
| -- | -------- |
| a  | d        | <- 'a' now follows 'd', creating a loop.
| b  | a        |
| c  | b        |
| d  | c        |

如果不存储一些有助于创建约束的附加信息,似乎无法解决这个问题。但我无法弄清楚哪些信息会有所帮助。 Postgresql 有EXCLUDE 约束,我想也许可以以某种方式使用重叠运算符。不知道如何解决这个问题,但我感觉它需要更新太多行,这会破坏将序列存储在链表中的全部意义。


更新: 这个想法是在数据库级别而不是应用程序级别确保列表的完整性。另一个无效状态的例子:

| id | after_id |
| -- | -------- |
| a  | null     |
| b  | d        | <- updated
| c  | b        |
| d  | c        |

或者其他:

| id | after_id |
| -- | -------- |
| a  | null     |
| b  | d        | <- updated: followed 'a', now follows 'd'
| c  | b        |
| d  | c        |
| e  | a        | <- updated: followed 'd', now follows 'a', unique constraint on after_id will not be violated this way

【问题讨论】:

  • 没有办法通过约束来解决这个问题。
  • 为什么还要和NULL约会,检查是否为NULL然后阻止更新

标签: postgresql database-design linked-list circular-reference adjacency-list


【解决方案1】:

This article 似乎与您的问题有关。它谈到了避免圈子并设置了一个触发器来这样做。

另外,如果您正在查看 PostgreSQL 14,则可以有一个 native query to detect cycles

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-12
  • 2015-02-19
  • 2011-03-18
相关资源
最近更新 更多