我在表中创建一个约束,以便 8 列中没有一列必须彼此相等。
我想这样做:
alter table mytable
add constraint no_duplicate_values
check (col_1 <> col_2 <> col__3 <> col__4 <> col__5 <> col__6 <> col__7 <> col__8);
但是这当然行不通,因为
<>
只接受两个操作数,左和右。
是否有一个优雅的、等效的单语句替代方案?
为此,您需要使用逻辑 AND 运算符。顺便说一句,据我所知,没有什么优雅的方法。你能试试这个吗:
CHECK (
col_1 <> col_2 AND
col_1 <> col_3 AND
col_1 <> col_4 AND
col_1 <> col_5 AND
col_1 <> col_6 AND
col_1 <> col_7 AND
col_1 <> col_8 AND
col_2 <> col_3 AND
col_2 <> col_4 AND
col_2 <> col_5 AND
col_2 <> col_6 AND
col_2 <> col_7 AND
col_2 <> col_8 AND
col_3 <> col_4 AND
col_3 <> col_5 AND
col_3 <> col_6 AND
col_3 <> col_7 AND
col_3 <> col_8 AND
col_4 <> col_5 AND
col_4 <> col_6 AND
col_4 <> col_7 AND
col_4 <> col_8 AND
col_5 <> col_6 AND
col_5 <> col_7 AND
col_5 <> col_8 AND
col_6 <> col_7 AND
col_6 <> col_8 AND
col_7 <> col_8
)
我建议一个简单的辅助函数
create or replace function row_unique(jr jsonb) returns boolean language sql as
$$
with t(v) as
(
select value from jsonb_each_text(jr) j
)
select count(v) = count(distinct(v)) from t;
$$
然后
alter table mytable add constraint no_duplicate_values
check (row_unique(to_jsonb(mytable)));
但是,正如 Thorsten Kettner 评论的那样,可能值得重新审视您的数据设计。