postgresql:有条件且无重复的联接 [英] postgresql : join with condition and without duplication

查看:106
本文介绍了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.

这篇关于postgresql:有条件且无重复的联接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆