问题
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