I have a product search query which returns rows similar to this:
| id | name | search tag |
| 1 | cat | furry |
| 1 | cat | ginger |
| 2 | dog | furry |
What I need to do is be able to get the single row that matches more than one search tag – for this example, a search for furry AND ginger returns no rows because there is only one search tag per row (this is because to get these results I’m using an INNER JOIN).
My question is, what do I need to do to be able to test for furry AND ginger in the query and return the cat but not the dog?
I’m doing this in PHP.
UPDATE
In order to cope with users putting in duplicate tags, a simple fix to the HAVING condition will return rows that have duplicate tags rather than ignoring them:
mysql> select id, name, group_concat(tag) as tags,
count(tag) as cnt from animals where tag in ('furry', 'ginger')
group by id HAVING cnt>=2;
You could first select the rows that have the desired tags, then group them by animal ID. Count how many results you get per animal and if it’s the same as the number of tags you wanted you got a match.