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