I have a table named store
and one named products
.
The data is structured like this:
Store table
ID NAME
1, 'red fruit store';
2, 'blue fruit store';
3, 'orange fruit store';
Fruits table
ID STORE_ID PRODUCT_NAME
1, 1, 'orange';
2, 1, 'apple';
3, 1, 'banana';
4, 2, 'apple';
5, 3, 'banana';
6, 3, 'pear';
Vegetables table
ID STORE_ID PRODUCT_NAME
1, 1, 'tomato';
2, 1, 'carrot';
3, 1, 'potato';
4, 2, 'cabbage';
5, 3, 'tomato';
6, 3, 'carrot';
So I want to select the store that has both orange and banana from the fruits table and tomato, carrot and potato from the vegetables table.
How can I do that?
EDIT
If I want to select the store having
- oranges
- one or multiple from (banana, apple pear)
- and tomato or carrot
How can I do that ?
You need a
join
between the tables, a condition on the results like:and then
group by s.id, s.name
to get only the stores that have both 'banana' and 'orange':If you need to check for more products you will have to change the list that is checked with
in
and the number ofhaving count(*) = ?
to be exactly the number of items in the list.Another way to get the results you want is with EXISTS:
Edit
For your edited question:
See the demo.
Results: