postgresql:有条件且无重复的联接
我有一个包含一系列唯一ID的表A。我有另一个表B,其中包含一些此ID,但不是每个ID,一个名为value的字段和另一个名为idcategory的字段。在此表B中,由于类别不同,id可能会出现几次。
I have a table A that contains a series of unique id. I have an other table B that contains some of this id but not each one of them, a field called value and a another field called idcategory. In this table B, id can appears several times because of differents categories.
我想以唯一的方式列出表A中的所有id,并以定义的类别(idcategorie = 1)列出表B中关联的特定值。表A中的ID不能出现在表B中,但是无论如何我都希望在最终结果中且无重复地获得此信息。
I want to list all my id in the table A in a unique way and the specific value associated in the table B in a defined categorie (idcategorie = 1). Id in the table A could not appear in the table B, but i want this information anyway in my final result and without duplication.
这里是一个例子:
表A
id
-----
1
2
3
4
5
6
7
8
表B
id | idcategory | value
------------------------
1 | 1 | red
1 | 2 | circle
2 | 1 | green
3 | 1 | blue
3 | 2 | square
4 | 1 | green
4 | 2 | circle
5 | 1 | red
5 | 2 | square
8 | 2 | circle
结果
id | idcategory | value
------------------------
1 | 1 | red
2 | 1 | green
3 | 1 | blue
4 | 1 | green
5 | 1 | red
6 | null | no value
7 | null | no value
8 | null | no value
在postgreSQL中实现此目标的最佳方法是什么? 左加入
? UNION
?
What is the best way to achieve this in postgreSQL ? LEFT JOIN
? UNION
?
您似乎想要一个左连接
:
select a.id, b.idcategory, b.value
from a left join
b
on b.id = a.id and b.idcategory = 1;
值
列的 NULL
而不是'no value'
。您可以 替换它,但是 NULL
通常可以达到这个目的。
The value
column has NULL
rather than 'no value'
. You can replace it, but NULL
usually serves that purpose.