Adding columns of two relations in postgresql

倖福魔咒の 提交于 2019-12-11 05:38:27

问题


I have two relations such as relation1 and relation2. relation1 has columns of A,B,C and relation2 has columns of D,E,F.

I want to add A of relation1 with D of relation2 where C = F. For the C values which do not exist in relation2 must appear and F values which do not appear in relation1 also must appear How to do this postgresql?


回答1:


Use a FULL [OUTER] JOIN to include rows from either side without a matching row on the other side:

SELECT COALESCE(r1.a, 0) + COALESCE(r2.d, 0) AS a_d
FROM   relation1      r1
FULL   JOIN relation2 r2 ON r1.c = r2.f

Also use COALESCE() to catch NULL values substituted for missing columns.



来源:https://stackoverflow.com/questions/17729837/adding-columns-of-two-relations-in-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!