获取与特定父ID不关联的所有ID

  • 本文关键字:ID 关联 获取 sql oracle
  • 更新时间 :
  • 英文 :


在我的数据库中有一个特定的子/父表结构:CHILD_TABLE:

| child_table |
|-------------|
| id          |
| node_id     |

APARENT_TABLE:

| parent_table |
|--------------|
| id           |
| node_id      |

和一个ASSOCIATION_TABLE:

| association_table |
|-------------------|
| parent_node       |
| child_node        |
(ManyToOne on both parent and child tables)

假设我们用测试数据加载它们:

-- child table
| id | node_id |
|----|---------|
| 1  | 1       |
| 2  | 2       |
| 3  | 3       |
-- parent table
| id | node_id |
|----|---------|
| 1  | 1       |
| 2  | 2       |
| 3  | 3       |
| 4  | 4       |
-- association table
| parent_id | child_id |
|-----------|----------|
| 1         | 1        |
| 2         | 1        |
| 2         | 2        |
| 3         | 3        |
| 4         | 1        |

给定父ID列表和单个父ID,我想找到与这些ID相关联的所有子ID,但不是单个子ID。

在上面的示例数据中,

  • 父id列表:(1, 2)
  • 单亲ID:4

结果应该是child.id = 2,因为该条目与parent.id = 4没有连接,但至少与给定的"父id"有一个连接。


编辑

我设法得到一些工作与减去一个结果在另一个:

SELECT child.id
FROM child_table child
WHERE child.node_id
IN (
SELECT assoc.child_node
FROM association_table assoc
WHERE assoc.parent_node
IN (
SELECT parent.node_id
FROM parent_table parent
WHERE parent.id IN (1, 2)
)
)
MINUS
SELECT child2.id
FROM child_table child2
WHERE child2.node_id
IN (
SELECT assoc2.child_node
FROM association_table assoc2
WHERE assoc2.parent_node
IN (
SELECT parent2.node_id
FROM parent_table parent2
WHERE parent2.id = 4
)
);

是否有一种替代/更简单的方法来做同样的事情?

您只需要关联表。从中选择给定父列表的所有子列表,从那里使用NOT EXISTS删除所有具有单个父id的子关联。(见演示)

select a1.child_id 
from association a1 
where a1.parent_id in (1,2) 
and not exists ( select null 
from association a2 
where a1.child_id = a2.child_id 
and a2.parent_id = 4
);

最新更新