Select in a many-to-many relationship in MySQL

Posted by Joff Williams on Stack Overflow See other posts from Stack Overflow or by Joff Williams
Published on 2010-06-08T22:30:41Z Indexed on 2010/06/08 23:52 UTC
Read the original article Hit count: 208

Filed under:

I have two tables in a MySQL database, Locations and Tags, and a third table LocationsTagsAssoc which associates the two tables and treats them as a many-to-many relationship.

Table structure is as follows:

Locations
---------
ID int (Primary Key)
Name varchar(128)

LocationsTagsAssoc
------------------
ID int (Primary Key)
LocationID int (Foreign Key)
TagID int (Foreign Key)

Tags
----
ID int (Primary Key)
Name varchar(128)

So each location can be tagged with multiple tagwords, and each tagword can be tagged to multiple locations.

What I want to do is select only Locations which are tagged with all of the tag names supplied. For example:

I want all locations which are tagged with both "trees" and "swings". Location "Park" should be selected, but location "Forest" should not.

Any insight would be appreciated. Thanks!

© Stack Overflow or respective owner

Related posts about mysql