首页 > 解决方案 > 如何检查给定列值的表中是否仅存在一个组合

问题描述

我有一个表,它有 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。

标签: oracleconstraintsunique

解决方案


选项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;

并且在两个表中都为两个列定义了唯一键。


推荐阅读