简体   繁体   English

Postgres / SQL 数据库:如何强制键/值对的唯一组合

[英]Postgres / SQL Databases: How to enforce unique combination of key/value Pairs

a new Project requires a dynamic datamodel, meaning that the Properties for a record are stored in a seperate table like this:一个新项目需要一个动态数据模型,这意味着记录的属性存储在一个单独的表中,如下所示:

Items:
ID | insertiondate
 1 | 2017-01-31


Properties:
ID | fk_Item_ID |     Key      |     Value
 1 |     1      |  referenceNr |       1
 2 |     1      |    office    |       O1

... ...

What i need now is a possibility to enforce that a "referenceNumber" in unique per "office".我现在需要的是在每个“办公室”中强制执行唯一的“referenceNumber”的可能性。

so the insertion into this table with the 2 values (1, O2) is ok as well as (2, O1) - but (1, O1) has to violate the Constraint.所以用 2 个值 (1, O2) 插入到这个表中和 (2, O1) 一样可以 - 但是 (1, O1) 必须违反约束。

Is there a simple way to handle this?有没有简单的方法来处理这个问题?

Even if the project really asks for some key/value entries, this doesn't seem to be true for referencenr and office as you want to apply constraints on the pair.即使项目确实要求输入一些键/值条目,这对于referencenroffice来说似乎也不是真的,因为您想对这对应用约束。 So simply put the two in your items table and add the constraint.因此,只需将两者放在您的项目表中并添加约束。

The only other option I see is to make the two one entry:我看到的唯一其他选择是将两个条目输入:

ID | fk_Item_ID | Key                  | Value
 1 |     1      | 'referenceNr/office' | '1/01'

I'd go for the first solution.我会选择第一个解决方案。 Have key/value pairs only where absolutely necessary (and where the DBMS may be oblivious as to their content and mutual relations).仅在绝对必要的情况下才拥有键/值对(并且 DBMS 可能不知道它们的内容和相互关系)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM