我已经准备好FIDDLE HERE
我有一个如下所示的父表。
+----------+------------+
| material | Attachment |
+----------+------------+
| 101 | 1 |
| 102 | 2 |
| 201 | 4 |
| 202 | 4 |
| 301 | 2 |
+----------+------------+
也如下表所示
+--------+-------+
| parent | child |
+--------+-------+
| 101 | 201 |
| 101 | 202 |
| 101 | 204 |
| 101 | 205 |
| 102 | 301 |
| 102 | 302 |
+--------+-------+
我正在尝试以以下格式获取孩子的附件。预期的输出。
+--------+-------+------------+
| parent | child | Attachment |
+--------+-------+------------+
| 101 | 201 | 4 |
| 101 | 202 | 4 |
| 101 | 204 | Child NA |
| 101 | 205 | Child NA |
| 102 | 301 | 2 |
| 102 | 302 | Child NA |
+--------+-------+------------+
我已经尝试过此查询。但是我得到了父母而不是孩子的依恋。
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 <>小提琴。
为了发表评论,您可以这样写:
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);