从另一个 table 获取 Child 的属性
Get attribute of Child from another table
我准备了一份FIDDLE HERE
我有一个 parent table 如下所示。
+----------+------------+
| material | Attachment |
+----------+------------+
| 101 | 1 |
| 102 | 2 |
| 201 | 4 |
| 202 | 4 |
| 301 | 2 |
+----------+------------+
还有如下关系table
+--------+-------+
| parent | child |
+--------+-------+
| 101 | 201 |
| 101 | 202 |
| 101 | 204 |
| 101 | 205 |
| 102 | 301 |
| 102 | 302 |
+--------+-------+
我正在尝试获取以下格式的 child 附件。
预期输出。
+--------+-------+------------+
| parent | child | Attachment |
+--------+-------+------------+
| 101 | 201 | 4 |
| 101 | 202 | 4 |
| 101 | 204 | Child NA |
| 101 | 205 | Child NA |
| 102 | 301 | 2 |
| 102 | 302 | Child NA |
+--------+-------+------------+
我试过这个查询。但是我得到的附件是 Parent 而不是 child.
select c.parent,c.child,Attachment from parent p
join child c
on p.material=c.parent
下面。
+--------+-------+------------+
| parent | child | Attachment |
+--------+-------+------------+
| 101 | 201 | 1 |
| 101 | 202 | 1 |
| 101 | 204 | 1 |
| 101 | 205 | 1 |
| 102 | 301 | 2 |
| 102 | 302 | 2 |
+--------+-------+------------+
我认为这是一个 left join
:
select r.parent, r.child, p.attachment
from relation r left join
parent p
on p.material = r.child;
这会产生 NULL
而不是 'Child NA'
。
Here 是一个 db<>fiddle.
根据您的评论,您可以这样写:
select c.parent,
c.child,
p.attachment
from child c
left join parent p on p.material = c.child
and
c.parent IN (select material from parent);
我准备了一份FIDDLE HERE
我有一个 parent table 如下所示。
+----------+------------+
| material | Attachment |
+----------+------------+
| 101 | 1 |
| 102 | 2 |
| 201 | 4 |
| 202 | 4 |
| 301 | 2 |
+----------+------------+
还有如下关系table
+--------+-------+
| parent | child |
+--------+-------+
| 101 | 201 |
| 101 | 202 |
| 101 | 204 |
| 101 | 205 |
| 102 | 301 |
| 102 | 302 |
+--------+-------+
我正在尝试获取以下格式的 child 附件。 预期输出。
+--------+-------+------------+
| parent | child | Attachment |
+--------+-------+------------+
| 101 | 201 | 4 |
| 101 | 202 | 4 |
| 101 | 204 | Child NA |
| 101 | 205 | Child NA |
| 102 | 301 | 2 |
| 102 | 302 | Child NA |
+--------+-------+------------+
我试过这个查询。但是我得到的附件是 Parent 而不是 child.
select c.parent,c.child,Attachment from parent p
join child c
on p.material=c.parent
下面。
+--------+-------+------------+
| parent | child | Attachment |
+--------+-------+------------+
| 101 | 201 | 1 |
| 101 | 202 | 1 |
| 101 | 204 | 1 |
| 101 | 205 | 1 |
| 102 | 301 | 2 |
| 102 | 302 | 2 |
+--------+-------+------------+
我认为这是一个 left join
:
select r.parent, r.child, p.attachment
from relation r left join
parent p
on p.material = r.child;
这会产生 NULL
而不是 'Child NA'
。
Here 是一个 db<>fiddle.
根据您的评论,您可以这样写:
select c.parent,
c.child,
p.attachment
from child c
left join parent p on p.material = c.child
and
c.parent IN (select material from parent);