Re: tricky query question
Date: 8 Nov 94 08:16:09 EST
Message-ID: <1994Nov8.081609.1_at_corp02.d51.lilly.com>
In article <khuisman.32.000E846A_at_wnet.gov.edmonton.ab.ca>, khuisman_at_wnet.gov.edmonton.ab.ca (Ken Huisman) writes:
> I have a table with a 1:M relationship to another table.
>
> I would like to do a query on the first table based on whether or not there
> exists related rows in the second table. The closest i have come is to just
> do a join and retrieve the data on the 1 side several times - but i dont want
> this because i only want to retrieve each row once.
>
> i would like something like this:
>
> select id from table1 where id is a member of ( select table1id from table2
> where blah blah blah...)
>
> kind of a set membership kind of thing.
>
> Is there a way to do this?
>
> many thanks.
>
>
> Ken
> khuisman_at_wnet.gov.edmonton.ab.ca
>
My understanding is that the EXISTS operator is for exactly this type of thing.
select dname, deptno from dept where exists ( select * from emp where dept.deptno = emp.deptno);
Note that this is a correlated subquery. The inner query will get executed once for every row in the outer query. My understanding is that it would go quickly because the subquery stops as soon as it gets 1 row.
Another option that might do what you want is to do a join, then use DISTINCT to get rid of duplicate rows.
select distinct dname, dept.deptno from dept, emp where dept.deptno = emp.deptno;
-- Bob Swisshelm | swisshelm_at_Lilly.com | 317 276 5472 Eli Lilly and Company | Lilly Corporate Center | Indianapolis, IN 46285Received on Tue Nov 08 1994 - 14:16:09 CET