如何加入并获得4个结果

时间:2017-05-17 06:34:16

标签: sql join left-join

我有2张桌子

A
artnr grp name
1 FlowerA NameA
2 FlowerB NameB
3 FlowerC NameC
4 FlowerD NameD

B
artnr eigenschap waarde
1 color Red
2 color Null
4 color Yellow
4 Height 30

如何获得4个带颜色的结果?

Select A.Artnr,
       A.grp,
       A.name,
       B.waarde
from A
left join B on B.Artnr = A.Artnr 
where B.Eigenschap = 'color'

我的问题是表B没有artnr 3,Artnr 2是空的(Is Null)没有问题。当两个表中都没有记录时,我遇到了问题。

我想要以下结果:

A left join b
artnr grp name   waarde
1 FlowerA NameA  red
2 FlowerB NameB  NULL
3 FlowerC NameC  NULL   -- Droptopp: I want to see this even not in table B
4 FlowerD NameD  yellow

我得到3行,缺少artnr 3的行,因为我认为它不在表B中。那么如何获得4行的结果,而artnr 3的行是列颜色的空单元格呢?

2 个答案:

答案 0 :(得分:0)

SELECT A.Artnr, A.grp, A.name, B.waarde
FROM A 
LEFT OUTER JOIN B 
ON (A.artnr = B.artnr)

What is the difference between "INNER JOIN" and "OUTER JOIN"?

答案 1 :(得分:0)

您的问题似乎是WHERE。这句话:

Select A.Artnr,
   A.grp,
   A.name,
   B.eigenschap,
   B.waarde
from A
left join B on B.Artnr = A.Artnr

将为第3条返回一行,即

3 FlowerC NameC NULL NULL

之后,您会过滤eigenschap = 'color',这会从eigenschap NULL后的最终结果集中删除该行。将该条件移动到连接条件:

Select A.Artnr,
   A.grp,
   A.name,
   B.waarde
from A
left join B on B.Artnr = A.Artnr AND
B.eigenschap = 'color'