如果另一个 table 中的值为真,postgres 添加一个不为空的约束

postgres add a constraint not null if value is true in another table

我想知道是否可以根据另一个 table 中另一列的值在一列上创建具有非空约束的 table。 (在 postgres 中)

示例:

CREATE TABLE IF NOT EXISTS Ref (
    id SERIAL PRIMARY KEY,
    required BOOLEAN DEFAULT FALSE
);

CREATE TABLE IF NOT EXISTS Value (
    id SERIAL PRIMARY KEY,
    refId INTEGER REFERENCES Ref(id) NOT NULL,
    value TEXT,
);

所以在这里我想添加一个约束 NOT NULL 到 value if required is TRUE。

所以我尝试使用一些检查,但它似乎只检查同一 table 内的列 :(.

提前致谢。

我了解到,当required字段等于true时,那么我们必须将Value table的字段设置为NOT NULL,否则设置为必须为NULL。 您可以使用 PostgreSQL 检查约束来执行此操作。首先我们必须创建一个函数来检查字段值。

CREATE OR REPLACE FUNCTION get_required(p_id integer, p_value text)
RETURNS BOOLEAN AS
$$
declare 
    v_ret bool;
begin
    select required into v_ret from tbl_ref where id = p_id;

    if (v_ret)and(p_value is null) then 
        return false; 
    end if;

    return true; 
END;
$$ LANGUAGE PLpgSQL;

然后我们可以在创建table过程中使用这个函数:

CREATE TABLE tbl_val (
    id serial4 NOT NULL,
    ref_id int4 NOT NULL,
    "value" text NULL,
    CONSTRAINT tbl_val_check CHECK (get_required(ref_id, "value")),
    CONSTRAINT tbl_val_pkey PRIMARY KEY (id),
    CONSTRAINT tbl_val_fk FOREIGN KEY (ref_id) REFERENCES tbl_ref(id)
);