I have a table (t0), in my Postgres DB, with data that looks something like this:
t1_id t2_id
1 1
2 1
2 1
4 null
4 null
5 null
And I have a query to return my desired results of:
t1_id t2_id
1 1
4 null
5 null
My query looks something like this:
(
SELECT DISTINCT ON (t2_id) t1_id, t2_id
FROM t0
WHERE t2_id IS NOT NULL
)
UNION ALL
(
SELECT DISTINCT ON (t1_id) t1_id, t2_id
FROM t0
WHERE t2_id IS NULL
)
Is there a faster way to do an operation like this? It's not too bad, but I'm doing it in several places (with joins) and all these repeated queries seems to slow stuff down a bit. Seems like there must be a better way.
Here's the query in fiddle form: http://sqlfiddle.com/#!15/d41d8/3603
union all:select distinct on (t2_id) t1_id, t2_id from t0will do just fine: http://sqlfiddle.com/#!15/d41d8/3591 Btw. the parentheses around the individual selects are totally useless for the union – Oct 12 '14 at 04:47I updated the question by adding another row
– Sam Oct 12 '14 at 06:255 nullto the data and query result.UNION ALL. It needsORDER BYfor theDISTINCT ONto have determinate results but that's irreleveant. Try adding a query you have and not strip it too much. – ypercubeᵀᴹ Oct 12 '14 at 11:095, null. It combines4 nulland5 nullwhich I want to keep separate. – Sam Oct 12 '14 at 16:45