I would like to JOIN two tables in Postgresql 9.5 ON two columns:
CREATE TABLE table_a (col1 INT, col2 INT, col3 TEXT);
CREATE TABLE table_b (col1 INT, col2 INT, col3 TEXT);
INSERT INTO table_a (col1, col2, col3)
VALUES (1, 2, 'foo'), (NULL, 3, 'foo');
INSERT INTO table_b (col1, col2, col3)
VALUES (1, 2, 'bar'), (NULL, 3, 'bar');
When I do the join
SELECT a.col3, b.col3
FROM table_a a
LEFT JOIN table_b b
ON a.col1 = b.col1 AND
a.col2 = b.col2;
the row with the null value is not joined.
a.col3 | b.col3
---------------
foo | bar
foo | <null>
However, I would like to have both columns joined, i.e. including the ones where one of the values is null. So there should be foo bar appearing twice in this example. How could I make this work?
ON coalesce(a.col1,-1) = coalesce(b.col1,-1) AND a.col2 = b.col2