Question

I have two tables, A and B. B is a random subset of A but with some values that override the default values in A. How do I join the two tables to coalesce their values?

A

1, 0
2, 0
3, 0
4, 0

B

2, 10
3, 11

Output

1, 0
2, 10
3, 11
4, 0

Here is my actual query - I thought I could do this with LEFT OUTER JOIN, but this restricts the Output set to the intersection of A and B rows. I need all A rows to return, coalesced with the relevant B rows.

SELECT A.factor, A.categorical_value, coalesce(A.positive, B.positive),  coalesce(A.negative, B.negative) 
FROM features A 
LEFT OUTER JOIN profiles B ON (A.factor=B.factor AND A.categorical_value=B.categorical_value)
WHERE B.uuid='9e5083da74305628336631da9d2903e3' 

As Craig Ringer points out below, I am inadvertently restricting A with my B clause. But then how do I do this? Table A is a many-to-many table of profile attributes, where uuid indicates the user id. Table B is a master list of all possible profile attributes. I want the query to return the master list with the an individual profile superimposed on to it.

Was it helpful?

Solution

After question update:

As @Craig already informed you, a WHERE condition on B would only select matching rows in B and act like a [INNER] JOIN instead of a LEFT [OUTER] JOIN.

You need to pull that WHERE condition up into the condition of the LEFT JOIN.
While being at it, I opportunistically simplified with USING, since all joining column names are identical. Details in the manual.

Information is still incomplete and contradicting. Here is another educated guess:

SELECT a.factor, a.categorical_value
     , COALESCE(a.positive, b.positive) AS positive
     , COALESCE(a.negative, b.negative) AS negative 
FROM   features a 
LEFT  JOIN profiles b USING (factor, categorical_value, uuid)
WHERE  a.uuid='9e5083da74305628336631da9d2903e3'

Not sure if you need to join on udid, too.
Your example would indicate COALESCE(b.positive, a.positive). Something does not add up ...

More updates in comment

Adapt your JOIN condition then:

SELECT a.factor, a.categorical_value
     , COALESCE(a.positive, b.positive) AS positive
     , COALESCE(a.negative, b.negative) AS negative 
FROM   features a 
LEFT   JOIN profiles b ON a.factor = b.factor
                      AND a.categorical_value = b.categorical_value
                      AND b.uuid='9e5083da74305628336631da9d2903e3';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top