I want to retrieve items which have certain filters set. For example list items which are red or blue and small should return only the item apple. ((red(2) or blue(4)) and small(5)) => apple
I have found 2 solutions, but both seem to me overly complex.
The first solution seems to me more elegant, as when I want to add another filter by AND
, its quite simple. While the second solution will require another JOIN
.
I hope I am overlooking something and there is a much better solution then this.
The questions,
- is there a better solution?
- if there is no better solution - which one is faster/recommended?
item table
| id | itemname |
├────┼──────────┤
| 1 | apple |
| 2 | orange |
| 3 | banana |
| 4 | melon |
filter table
│ id │ filtername │
├────┼────────────┤
│ 1 │ orange │
│ 2 │ red │
│ 3 │ green │
│ 4 │ blue │
│ 5 │ small │
│ 6 │ medium │
│ 7 │ big │
│ 8 │ yellow │
item_filter
│ item_id │ filter_id │
├─────────┼───────────┤
│ 1 │ 2 │
│ 1 │ 3 │
│ 1 │ 5 │
│ 2 │ 1 │
│ 2 │ 5 │
│ 3 │ 6 │
│ 3 │ 8 │
│ 4 │ 3 │
│ 4 │ 7 │
First solution based on GROUP_CONCAT and FIND_IN_SET
sqlfiddle: http://sqlfiddle.com/#!9/26f99/1/0
SELECT * FROM item
JOIN (
SELECT item_id, GROUP_CONCAT(filter_id) AS filters
FROM item_filter
GROUP BY item_id
) AS grp ON grp.item_id = item.id
WHERE (FIND_IN_SET(2,filters) OR FIND_IN_SET(4,filters)) AND FIND_IN_SET(5, filters)
Second solution based on JOIN and where clause only
sqlfiddle: http://sqlfiddle.com/#!9/f0b95/1/0
SELECT itemname FROM item
JOIN item_filter as filter1 on item.id=filter1.item_id
JOIN item_filter as filter2 on item.id=filter2.item_id
WHERE (filter1.filter_id=2 or filter1.filter_id=4) and filter2.filter_id=5