MySQL Forums
Forum List  »  Newbie

Re: Help with select statement
Posted by: Chris Stubben
Date: May 03, 2005 09:37AM

Hi,

If the id and skill combination are unique (unique key (id, skill)), you can just count the number of rows using an aggregate function and add a HAVING clause...


create table tmp(id int, skill char(1));
insert into tmp values (1,'a'), (1,'b'), (1,'c'), (2,'a'), (2,'c'), (3,'b');

NOTE: (skill='a' or skill='b') is the same as skill in ('a', 'b')


select id from tmp where id=1 and skill in ('a', 'b') group by id having count(*)=2;
+------+
| id |
+------+
| 1 |
+------+

select id from tmp where id=2 and skill in ('a', 'b') group by id having count(*)=2;

Empty set (0.00 sec)

or search ALL rows

select id from tmp where skill in ('a', 'b') group by id having count(*)=2;


---
You can also use a subselect or self-join ...


select DISTINCT id from tmp where id in (select id from tmp where skill='a') and id in (select id from tmp where skill='b');
+------+
| id |
+------+
| 1 |
+------+


or self join (one join needed for each skill)

select t1.id, t1.skill, t2.skill from tmp t1, tmp t2
where t1.id=t2.id and t1.skill='a' and t2.skill= 'b';
+------+-------+-------+
| id | skill | skill |
+------+-------+-------+
| 1 | a | b |
+------+-------+-------+


Chris

Options: ReplyQuote


Subject
Written By
Posted
May 02, 2005 11:02AM
Re: Help with select statement
May 03, 2005 09:37AM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.