一列具有唯一约束,而另一列具有相同值则排除行 [英] Unique constraint on one column with excluding row with same values in other

查看:109
本文介绍了一列具有唯一约束,而另一列具有相同值则排除行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 value 列中添加唯一键,但是我必须忽略在 value header_id 。例如,请考虑以下表格:

I'd like to add a unique key to column value but I must ignore rows that have the same values in columns value and header_id. For example, consider this table:

id | header_id | value
 1 |         1 | a
 2 |         1 | a
 3 |         2 | a

所以第1行和第2行指向同一对象,唯一键应接受它们,但第3行具有不同的 header_id (指向另一个对象),并且由于它具有与对象1相同的 value 值,因此应该违反唯一约束并引发错误。

So rows 1 and 2 point to same object and the unique key should accept them, but row 3 has a different header_id (pointing to another object) and, because it has the same value as object 1, it should violate unique constraint and raise an error.

编辑16.2:1327:

我正在使用一个核心框架生成用于处理历史记录的列,因此无法规范化表。我的班级有很多列,但在此示例中,我仅考虑 value 列。

推荐答案

一段时间后,我发现了一些东西。使用带有功能的约束CHECK来确定是否存在(不能在CHECK语句中使用SELECT,但是可以将功能与所需的select一起使用)

After a while I found something. Using constrain CHECK with function to determine if exist (Cannot use SELECT in CHECK statement but you can use function with desired select)

CREATE OR REPLACE FUNCTION is_value_free(_header_id integer, _value varchar) RETURNS BOOLEAN AS 
$$
  BEGIN
    RETURN NOT EXISTS (SELECT header_id,value FROM myschema.mytalbe WHERE value LIKE _value AND header_id != _header_id LIMIT 1);
  END;
$$ LANGUAGE plpgsql;

ALTER TABLE mytable ADD CONSTRAINT uniq_value CHECK (is_value_free(header_id,value))

这篇关于一列具有唯一约束,而另一列具有相同值则排除行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆