Suppose it's a website that sells photo cameras. Here are my entities (tables):
Camera: A simple camera
Feature: A feature like: 6mp, max resolution 1024x768,
The thing is between cameras and feature i've got a Many to Many relationship, so i have an extra table:
camera -> cameras_features -> feature
So, the query is simple:
How to get all the cameras that have the feature 1,2 and 3?
It's like constructing a bitmap index.
Data you can use to test if the solution is ok
C1 has features 1,2,3
C2 has features 1,2,4
C3 has features 1,2
Here are querys and the expected result:
- Show all the cameras which have feature 1,2 and 3: C1
- Show all the cameras which have feature 1,2 and 4: C2
- Show all the cameras which have feature 1 and 2: C1, C2 and C3
Here is what i did (it works, but it's really ugly, don't want to use it):
SELECT * FROM camera c
WHERE c.id IN (
(SELECT c.id FROM camera c JOIN cameras_features f ON (c.id=f.camera_id)
WHERE f.feature_id=1)
q1 JOIN -- simple intersect
(SELECT c.id FROM camera c JOIN cameras_features f ON (c.id=f.camera_id)
WHERE f.feature_id=2)
q2 JOIN ON (q1.id=q2.id)
)
3
is the number of features in(1,2,3)
. And assuming(camera_id,feature_id)
is unique incamera_features
.What is happening here is that cameras will be filtered down to cameras with feature 1, then within this group, the cameras are gonna be filtered down to the ones with feature 2
This is easiest to generalise by putting the search values into a table...