postgresql - 基于表值的 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 上使用的所有芯”
谢谢,
解决方案
我认为您需要的是检查约束之类的东西。(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);
希望这可以帮助 !
推荐阅读
- java - 在 Java Batch 中更新数百万行的最佳方法
- javascript - Node.js-null不等于0或大于0但大于等于0
- javascript - OnRefresh State Persist 包含 100 张图像?
- reactjs - Axios Reactjs 中的响应时间
- javascript - Chrome DevTools 内存不一致
- php - 从身份提供者发起的单点登录流程
- arrays - 获取数组值并在c中对数组进行排序时出现分段错误。?
- c++ - 未命名命名空间中“使用命名空间”的范围
- spotfire - Tibco - 基于计划与实际的 S 曲线
- spring - 如何在spring RESTful中更改控制器后的值