首页 > 解决方案 > 基于表值的 Postgresql 数据验证检查

问题描述

我正在尝试创建一个跟踪电缆的数据库。每条电缆包含 1 个或多个芯线,这些芯线连接到每端的端子。每条电缆中的芯数在表格中定义。

| number_of_cores  | cable_id
|----------2-------|---1-----|

核心表如下

cable_no   | from_id | core_mark | to_id
1001       |       1 | 1 Black   |     2
1001       |       2 | 1 White   |     4

我想创建一个检查,以防止插入另一个 1001 电缆芯。

这在postgresql中可能吗?

理想情况下,如果我尝试插入另一条具有另一个唯一芯数的 1001 电缆,则错误将类似于“电缆 1001 上使用的所有芯”

谢谢,

标签: postgresql

解决方案


我认为您需要的是检查约束之类的东西。(https://www.postgresql.org/docs/current/ddl-constraints.html

请按照以下步骤操作:

1.正确创建一些表

create table cable (cable_id int primary key, number_of_cores int);
create table core (core_id int primary key, cable_id int references cable (cable_id), from_id int, core_mark varchar (50), to_id int);

2. 创建验证插入的函数

create or replace function test_max_core_number(in_cable_id int)
 returns boolean
 language plpgsql
as $function$
declare
    res boolean := false;
begin
    if exists (
        select *
        from cable 
        where cable_id = in_cable_id
            and number_of_cores > (select count(*) from core where cable_id = in_cable_id )
    )
    then 
        res := true;
    end if;

    return res;
end;
$function$;

3. 将约束添加到您的表中

alter table core 
add constraint cstr_check check (test_max_core_number(cable_id));

4. 现在是时候进行一些测试了 :)

insert into cable (cable_id, number_of_cores) values (1, 2), (2, 3);
insert into core (core_id, cable_id, from_id, core_mark, to_id)
values
    (1, 1, 1, '1 Black', 2)
    ,(2, 1, 2, '1 White', 4);

通常现在一切都很好。

5.现在是通缉的错误!

insert into core (core_id, cable_id, from_id, core_mark, to_id)
values
    (3, 1, 3, '1 Green', 2);

希望这可以帮助 !


推荐阅读