在我的資料庫中,有一個特定的子表/母表結構。
CHILD_TABLE:
| child_table |
|-------------|
| id |
|節點_id |
一個PARENT_TABLE:
| parent_table |
|--------------|
| id |
|節點_id |
和一個ASSOCIATION_TABLE:
| association_table |
|-------------------|
| parent_node |
| child_node |
(ManyToOne on both parent and children tables)
假設我們用測驗資料加載它們:
--子表。
| id | node_id |
|----|---------|
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
-- parent table
| id | node_id|
|----|---------|
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 4 |
--關聯表
| 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沒有聯系,但與給定的 "父IDs "至少有一個聯系。
編輯
我設法用一個結果減去另一個結果來獲得一些作業:
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)
)
)
減去
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
)
);
是否有一個替代的/更簡單的方法來做同樣的事情?
uj5u.com熱心網友回復:
你只需要關聯表。從中選擇給定的父串列的所有孩子,從那里使用NOT EXISTS來洗掉所有與單一父id相關的孩子。(見demo)
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
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/332521.html
標籤:
