Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Opposite of UNION ... 2

Status
Not open for further replies.

grega

Programmer
Feb 2, 2000
932
GB
All, my heads hurting at this one today so I need a bit of help. I have a table with the following data;
[tt]
key val
----------
a 100
a 200
a 300
b 200
c 200
c 300
[/tt]
I want to find all keys which have a val of both 200 and 300, and just cannot find a way. I've tried this ...
Code:
select key from table where val=200
union
select key from table where val=300
which will return keys a,b,c. What I need is a way to join the 2 result sets, only including rows present in both sets.

Any ideas much appreciated. I'm running Sybase ASE 11.5.

Greg.
 
try intersect instead of union

or..

select a.key from table a
where a.val =200
and exists (select 1 from table b
where a.key = b.key
and a.val = 300)
 
Greg -
Try this:

select key from table where val=200
INTERSECT
select key from table where val=300;

It works in Oracle, and I think it's pretty standard SQL.
 
Just for your future reference, besides UNION and UNION ALL;
INTERSECT and INTERSECT ALL, there is also quite often a set operator MINUS (or sometimes EXCEPT). Rarely needed, but handy to know about. Malcolm
 
I think the best sollution is:
select p.key from
(select key from table where val=200) p
inner join
(select key from table where val=300) t
on
p.key=t.key
where ...

John Fill
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top