Re: joining two simular (but not identical tables)

From: Michael Fuhr <mike(at)fuhr(dot)org>
To: Neil Dugan <postgres(at)butterflystitches(dot)com(dot)au>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: joining two simular (but not identical tables)
Date: 2005-09-04 13:00:31
Message-ID: 20050904130031.GA9978@winnie.fuhr.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Sun, Sep 04, 2005 at 10:19:12PM +1000, Neil Dugan wrote:
> I have two similar but not identical tables.
> I would like to create a view that combines the contents of both tables
> into a single view, where each record in each table is visible as a
> separate record in the view.

Sounds like you're looking for UNION.

http://www.postgresql.org/docs/8.0/static/queries-union.html
http://www.postgresql.org/docs/8.0/static/typeconv-union-case.html

Does the following example do what you want?

CREATE TABLE a (x integer, y integer);
INSERT INTO a (x, y) VALUES (1, 2);
INSERT INTO a (x, y) VALUES (3, 4);

CREATE TABLE b (x integer, z integer);
INSERT INTO b (x, z) VALUES (5, 6);
INSERT INTO b (x, z) VALUES (7, 8);

CREATE VIEW v AS
SELECT x, y, NULL AS z FROM a
UNION ALL
SELECT x, NULL AS y, z FROM b;

SELECT * FROM v;
x | y | z
---+---+---
1 | 2 |
3 | 4 |
5 | | 6
7 | | 8
(4 rows)

--
Michael Fuhr

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Andreas Joseph Krogh 2005-09-04 17:14:25 Help with UNION query
Previous Message Neil Dugan 2005-09-04 12:19:12 joining two simular (but not identical tables)