Help with UNION query

From: Andreas Joseph Krogh <andreak(at)officenet(dot)no>
To: pgsql-sql(at)postgresql(dot)org
Subject: Help with UNION query
Date: 2005-09-04 17:14:25
Message-ID: 200509041914.33245.andreak@officenet.no
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Hi all, I have the followin query:

SELECT g.id
from onp_group g
where g.groupname IN
(SELECT ug.groupname from onp_user_group ug WHERE ug.username = 'andreak')
UNION (SELECT child_id
FROM onp_group_children
WHERE group_id IN
(SELECT g.id from onp_group g
where g.groupname IN (SELECT ug.groupname from onp_user_group ug WHERE
ug.username = 'andreak')));

Any ideas on how I can simplyfy this query so that I only need to provide
ug.username='andreak' once? I would much rather prefer a query which doesn't
involve UNION or SUB-SELECTS.

Here are the table-definitions:

CREATE TABLE onp_group(
id integer PRIMARY KEY REFERENCES onp_entity(id) on delete cascade,
p_id integer REFERENCES onp_group(id) on delete cascade,
groupname varchar NOT NULL unique
);

CREATE TABLE onp_group_children(
group_id integer NOT NULL REFERENCES onp_group(id),
child_id integer NOT NULL REFERENCES onp_group(id),
UNIQUE(group_id, child_id)
);

CREATE TABLE onp_user_group(
groupname varchar not null REFERENCES onp_group(groupname) ON DELETE CASCADE
ON UPDATE CASCADE,
username varchar not null REFERENCES onp_user(username) ON DELETE CASCADE ON
UPDATE CASCADE,
primary key(groupname, username)
);

--
Andreas Joseph Krogh <andreak(at)officenet(dot)no>
Senior Software Developer / Manager
gpg public_key: http://dev.officenet.no/~andreak/public_key.asc
------------------------+---------------------------------------------+
OfficeNet AS | The most difficult thing in the world is to |
Hoffsveien 17 | know how to do a thing and to watch |
PO. Box 425 Skøyen | somebody else doing it wrong, without |
0213 Oslo | comment. |
NORWAY | |
Phone : +47 22 13 01 00 | |
Direct: +47 22 13 10 03 | |
Mobile: +47 909 56 963 | |
------------------------+---------------------------------------------+

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Andreas Joseph Krogh 2005-09-04 18:08:20 Re: Help with UNION query
Previous Message Michael Fuhr 2005-09-04 13:00:31 Re: joining two simular (but not identical tables)