Postgres,在2列之间创建值的唯一性

时间:2015-04-01 17:18:35

标签: mysql postgresql

并提前感谢任何有能力提供帮助的人。我有这张表,如下所示。

表INVOICE


ID | delivery_statement_id | supply_statement_id

_ | 1 | 2

_ | 3 | 4

_ | 2 | 4< -Should不会传递给DB,因为id 2已在第一行中使用过。

我想确保在整个数据库的两列之间存在唯一的ID

如果使用了statement_id 1,则永远不能再次使用它来传递或提供声明。 请帮忙,当我搜索这个问题时,我不断获得多列的索引,但这只能解决行组合的问题。

谢谢

1 个答案:

答案 0 :(得分:0)

我的理解是,您有一个具有以下结构的表:

"invoice"
(
id (primary key),
delivery_statement_id,
supply_statement_id
)

根据列的名称判断,“delivery_statement_id”和“supply_statement_id”是同一个外部表的外键......比方说,它们是指“声明”

"invoice"
(
id (primary key),
delivery_statement_id -> statement(id),
supply_statement_id -> statement(id)
)

如果你有一个表“声明”,并且你想避免从“delivery_statement_id”和“supply_statement_id”获得多个引用 - 我的建议是将“invoice_id”列添加到“声明”表中:

"statement"
(
id (primary key),
/** some other columns **/
invoice_id (nullable, with unique constraint) -> invoice(id)
)

所以首先在“statement”中创建行而不引用任何发票 然后设置delivery_statement_id和supply_statement_id 并且在设置每个值之后,您必须在“声明”表中“注册”它...这可以很容易地作为触发器实现,附加到“发票”表