I don't know if my title correctly conveys the query I'm trying to achieve, so please edit or suggest a better one that is more correct. I'm trying to join these two tables together:
Table 1: people
id |field1|field2|
------------------
1
2
3
4
.
.
. (etc)
Table 2: foods
person.id | name
1 | chicken
1 | pork
1 | beef
2 | pork
2 | chicken
3 | chicken
4 | beef
.
. (etc)
I need to join these tables based on a search for any people whose ID is matched with both pork or chicken. For example, if I search for pork
, 1 and 2 should be returned, and if I search for pork
and chicken
, 1 and 2 should still be returned, but 3 will not be because it doesn't match chicken
as well as pork
. If I search for pork
, chicken
, and beef
, only 1 should be returned.
I've been looking at this question, but I don't know how many items I'll be searching for (I could be searching for pork
and chicken
one time, and pork
, chicken
, or beef
another time).
I started out trying the basic WHERE
clause, which I was fairly certain was faulty (I confirmed this because the query didn't work):
SELECT p.id
FROM people p, foods f
WHERE p.id = f.person_id AND (f.name = 'pork' AND f.name = 'chicken')
but this returns no results. I seem to remember from an SQL tutorial several years ago that I should be using the EXISTS
keyword along with a subquery, but I'm not sure how to shape my query/queries based on that.
EDIT: SQL Server CE doesn't support the INTERSECT
keyword, so unfortunately that option isn't available to me.