复杂键约束:仅当 uuid 是新的或另一列匹配时才允许

jak*_*sco 3 sql-server constraint azure-sql-database

对于我的用例,我试图让这样的东西与 Azure 数据工厂(ADF)一起使用

但我也从理论的角度对这个问题感兴趣。是否可以在像 postgres 这样的普通 SQL 引擎中做这样的事情?

我想禁止基于此键插入: (non_unique_id, timestamp) 其中时间戳是该对的唯一值。

例如:

要插入的数据:

non_unique_id: 0cf6c19c14
timestamp: 1970-01-01 00:00:01
Run Code Online (Sandbox Code Playgroud)

情况 1 允许

插入前:

select non_unique_id, timestamp from tbl where non_unique_id = 0cf6c19c14;

0 results
Run Code Online (Sandbox Code Playgroud)

情况 2 允许

插入前:

select non_unique_id, timestamp from tbl where non_unique_id = 0cf6c19c14;

0cf6c19c14, 1970-01-01 00:00:01
0cf6c19c14, 1970-01-01 00:00:01
0cf6c19c14, 1970-01-01 00:00:01
...
Run Code Online (Sandbox Code Playgroud)

情况 3 不允许

插入前:

select non_unique_id, timestamp from tbl where non_unique_id = 0cf6c19c14;

0cf6c19c14, 2038-01-19 03:14:05
0cf6c19c14, 2038-01-19 03:14:05
0cf6c19c14, 2038-01-19 03:14:05
...
Run Code Online (Sandbox Code Playgroud)

当然还有其他列,但这说明了最简单的情况

Mar*_*ith 5

这是一个规范化问题,因为时间戳在功能上依赖于non_unique_id.

所以应该有另一个带有主键non_unique_id和相应时间戳的表。

在 SQL Server/Azure SQL 数据库中,您可以使用索引视图强制执行此操作。

创建具有模式绑定和定义的视图

SELECT non_unique_id,
       timestamp,
       COUNT_BIG(non_unique_id) AS Count
FROM   dbo.YourTable
GROUP  BY non_unique_id,
          timestamp 
Run Code Online (Sandbox Code Playgroud)

然后non_unique_id在视图中的列上放置一个唯一的聚集索引。