PostgreSQL – How to Merge Join Results

join;postgresqlselect

I have 2 tables with common columns and would like to know if it's possible to request this 2 tables by merging the results.

Table "job" : parent_id, target_id, start_date, end_date, jobposition_id

Table "study" : parent_id, target_id, start_date, end_date

At this moment if I do something like :

SELECT *
FROM user AS u 
LEFT JOIN study AS s ON s.parent_id=u.id OR s.target_id=u.id 
LEFT JOIN job AS j ON j.parent_id=u.id OR j.target_id=u.id
WHERE u.id=2;

I got a resultset with every common column doubled (I have 2 times parent_id, target_id, start_date, end_date).

How can I get a simple resultset with only one column parent_id, etc (and a jobposition_id column set to NULL for every study result) ?

Thanks

Best Answer

I hope to have fully understood your request. With this query you get a concatenation of tables (a UNION) with all records.

SELECT parent_id, target_id, start_date, end_date, NULL AS jobposition_id FROM study
UNION ALL
SELECT parent_id, target_id, start_date, end_date, jobposition_id FROM job

You can play with UNION to obtain the merging concept you have in mind. Here's a link to the official documentation (PostgreSQL 9.4): UNION clause. I think that you would like to remove duplicates (if there are duplicate entries in both tables), so probably the UNION DISTINCT is right for you.