I have an objects, tags, and tag_relationships table. Objects and tags each have an id column, and tag_relationships connects the two.
Sample of tag_relationships (used in example below):
+--------+--------+
| obj_id | tag_id |
+--------+--------+
| 1 | 1 |
| 1 | 2 |
| 2 | 1 |
| 2 | 3 |
| 2 | 4 |
+--------+--------+
I want to implement an AND search to allow people to filter tags. Only obj_ids that have a row with the all of the given tag_ids should be returned. For example:
Sample input: 1, 3 (would actually be tag names, but they would converted to ids)
Desired output: 2
It feels like this should be easy, but for the life of me I can’t figure out a simple way to do this. I’m currently thinking of returning a table with all the rows in tag_relationships that have one of the given tag_ids, then sorting through them with PHP. Is there a simpler, SQL-only method?
You can use the
HAVINGclause in conjunction withGROUP BYto answer questions involving all of something…The
2in theCOUNT(*)represents the number of tags you are searching on. If you wanted objects that satisfied say, three tags… (e.g.1,3,6), you would up theCOUNT(*)to3.