Re: Question About UNION

From: Bill Thoen <bthoen(at)gisnet(dot)com>
To: Josh Williams <joshwilliams(at)ij(dot)net>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Question About UNION
Date: 2008-10-09 20:06:23
Message-ID: 48EE643F.4000909@gisnet.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Josh Williams wrote:
> On Thu, 2008-10-09 at 10:59 -0600, Bill Thoen wrote:
>
>>>> I'm trying to combine two tables, but I only want unique records based
>>>> on the first two columns. Can UNION be used to join three-column tables
>>>> but only include records based on the uniqueness of the first two
>>>> columns? If not, how would I do this with PostgreSQL 8.1?
>>>>
>>> How do you decide which records you want? - e.g. given the following rows...
>>>
>>> (a, b, c)
>>> (a, b, d)
>>>
>>> ...how do you decide whether you the one with c or the one with d?
>>>
>>>
>>>
>> The physical order that they appear will take care of that.
>>
>
> If the rest of the columns don't matter, how about:
>
> SELECT DISTINCT ON(col1, col2) * FROM (
> SELECT col1, col2, col3 FROM table1
> UNION
> SELECT col1, col2, col3 FROM table2
> ORDER BY col1, col2
> ) AS uniontable;
>
> - Josh Williams
>
Great! This works too.
And to correct my last post, David Wilson had it right the SECOND time.
I've been wrestling with this stupid problem all morning and now my mind
is so gone I don't even trust whether I can get 'SELECT * FROM table1;'
to work!

Thanks for the help once again everybody!!!

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Martin Pitt 2008-10-09 20:15:27 Re: [Pkg-postgresql-public] Postgres major version support policy on Debian
Previous Message Raymond O'Donnell 2008-10-09 19:52:17 Fwd: Set-valued function in wrong context