X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [200.46.204.144]) by svr1.postgresql.org (Postfix) with ESMTP id 4E4AC3A4BE5 for ; Fri, 19 Nov 2004 19:42:46 +0000 (GMT) Received: from svr1.postgresql.org ([200.46.204.71]) by localhost (av.hub.org [200.46.204.144]) (amavisd-new, port 10024) with ESMTP id 29862-10 for ; Fri, 19 Nov 2004 19:42:36 +0000 (GMT) Received: from news.hub.org (news.hub.org [200.46.204.72]) by svr1.postgresql.org (Postfix) with ESMTP id 6EA423A4C65 for ; Fri, 19 Nov 2004 19:42:36 +0000 (GMT) Received: from news.hub.org (news.hub.org [200.46.204.72]) by news.hub.org (8.12.9/8.12.9) with ESMTP id iAJJgZsp033458 for ; Fri, 19 Nov 2004 19:42:35 GMT (envelope-from news@news.hub.org) Received: (from news@localhost) by news.hub.org (8.12.9/8.12.9/Submit) id iAJJNhdl027318 for pgsql-sql@postgresql.org; Fri, 19 Nov 2004 19:23:43 GMT Message-ID: <419E4A4C.9010307@activestateway.com> From: Mischa Sandberg Reply-To: ischamay.andbergsay@activestateway.com User-Agent: Mozilla Thunderbird 0.7.3 (X11/20040803) X-Accept-Language: en-us, en MIME-Version: 1.0 X-Newsgroups: comp.databases.postgresql.sql Subject: Re: SQL Question References: In-Reply-To: Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit Lines: 32 Date: Fri, 19 Nov 2004 19:23:43 GMT To: pgsql-sql@postgresql.org X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, hits=1.1 tagged_above=0.0 required=5.0 tests=NO_DNS_FOR_FROM X-Spam-Level: * X-Archive-Number: 200411/224 X-Sequence-Number: 19543 Igor Kryltsov wrote: > We have table > create table group_facility ( > group_id integer not null, > facility_id integer not null > ) > It stores facilities membership in group. For example: "North Region" - > facilityA, facilityB > I need to extract groups from this table which contain facilityN AND > facilityZ and may be others but these two(both) has to be a group member. > > Query: > SELECT DISTINCT group_id FROM facility_group s1 > WHERE EXISTS (SELECT 1 FROM facility_group s2 WHERE s2.group_id = > s1.group_id AND facility_id = 390) > AND > EXISTS (SELECT 1 FROM facility_group s2 WHERE s2.group_id = s1.group_id AND > facility_id = 999) > > works but what if I need to find groups where membership is (facilityN1, > ....facilityN100)?? Okay: suppose you have table my_facilities(facility_id integer) --- your facilityN1...facilityN100 SELECT group_id FROM facility_group s1 JOIN my_facilities s2 USING(facility_id) GROUP BY group_id HAVING COUNT(*) = (SELECT COUNT(*) FROM my_facilities)