oracle - 如何检查给定列值的表中是否仅存在一个组合
问题描述
我有一个表,它有 3 列孩子、父母和祖父母。子列是主键。多个孩子可以向同一个家长报告。
目前,我的表格有 4 个孩子向同一个父母报告,所以我将在表格中有 4 行。由于所有 4 个孩子的父母都是相同的,我希望祖父母也应该是相同的。
但是对于某些记录,祖父值是不同的,这是一个问题,我想添加一个约束或其他东西来防止这种情况发生。
例如,我的表格如下所示
Child | Parent | GrandParent |
10001 | 101 | 700 |
10002 | 101 | 700 |
10003 | 101 | 701 |
10004 | 101 | 700 |
第 4 个孩子 10003 向父母 101 报告,但祖父母不同,我想防止它发生。
Parent / GrandParent 组合上的通常唯一键约束将不起作用,因为这两列可以有重复的值。我无法为三列添加约束,因为它不会阻止上述情况的发生。
你能告诉我如何实现这一目标吗?我正在使用 Oracle 12c。
解决方案
选项1。
正如评论中所说,祖父母列不是必需的。父母-祖父母关系即与子-父母相同的关系。
喜欢:
select a.child, a.parent, b.parent
from parentchild a
, parentchild b
where b.child = a.parent
选项 2。
但是,如果您坚持使用此表布局,则可以在表上定义一个插入或更新前触发器,以检查表中是否存在具有相同父级但不同祖父级的记录。如果找到这样的行,触发器应该失败并标记错误,否则可以插入或更新记录。
触发器示例代码:
create trigger parentchild_iu
before insert or update
on parentchild for each row
declare
v_count number;
begin
select count(*) into v_count
from parentchild p
where p.parent = :new.parent
and p.grandparent != :new.grandparent;
if v_count != 0 then
raise_application_error("Parent/Grandparent combination invalid.");
end if;
end;
选项 3。
作为第三个选项,您可以将表分成两个表:childparent 和 parentgranparent,并具有以下查询:
select a.child, a.parent, b.grandparent
from childparent a
, parentgrandparent b
where a.parent = b.parent;
并且在两个表中都为两个列定义了唯一键。
推荐阅读
- postman - 使用 postman 捕获 http 请求(Postman 拦截器不会将 http 请求数据传递给 postman)
- android - 后退按钮关闭应用程序而不是转到上一个片段 android 导航组件
- excel - 选择项目时更新主目录表中行的日期列
- css - 散景图覆盖其他内容
- jenkins - 更改 Jenkins 用户密码后,Jenkins 节点终止
- java - Java 64 位安装不起作用;只有32位吗?
- python - 查找 Series 值发生显着变化的索引值
- spring-boot - @Autowired 在 Spring Boot 中为 Null,但同样可以通过 Application Context 访问
- javascript - 带有语义 UI 的搜索输入 React OnChange 非常慢
- c++ - 为什么我的编译器将字符串视为 const char[]?