I am working with a many-to-many relationship in MySQL as in the simplified example below. What I would like to do is given a category id, find the objects that are in that category and ONLY that category.
I can easily get all of the objects in a category:
SELECT * from object INNER JOIN link ON object.objectID = link.objectID WHERE link.categoryID=1;
This gives me object1 and object2, however what I want is just object1 as object2 is also in category2.
The only thing I could think of was using this as a subquery to get all the links for those object ids and then getting the ones with a count of 1.
I’m hoping there is a simpler and more efficient way!
-- Table: object
+---------+-----------+
| id | name |
+---------+-----------+
| 1 | object1 |
| 2 | object2 |
+---------+-----------+
-- Table: category
+------+-----------+
| id | name |
+------+-----------+
| 1 | category1 |
| 2 | category2 |
+------+---------+
-- Table: link
+-----------+-------------+
| objectid | categoryid |
+-----------+-------------+
| 1 | 1 |
| 2 | 1 |
| 2 | 2 |
+-----------+-------------+
You can group the
linktable by object and filter for only those groups containing one record: