MySql query over many-to-many relationship
-
05-07-2019 - |
Question
A very simple example of a n:m relationship that puzzles me. Let's assume we have two tables "Plant" and "Attribute" and another table between them holding their relationship with their IDs:
Plant--------hasAttribute--------Attribute
P1 | A1
P1 | A2
P1 | A3
P2 | A1
P2 | A2
P3 | A2
P3 | A3
So, Plant 1 has Attributes 1,2 and 3. Plant 2 has Attributes 1 and 2 and Plant 3 has Attributes 2 and 3. Now, in one single query, how can I get e.g. all the Plants that have Attribute 2 and 3? The result should return P1 and P3 because they both have Attributes 2 and 3. I was trying union but that will give me P2 as a result as well... any ideas?
Solution
SQL query that gives distinct results that match multiple columns
Is this what your looking for?
OTHER TIPS
This query structure avoids the need for a distinct clause (provided there are no duplicate records in the resolution table).
SELECT p.PlantID
FROM
Plant p INNER JOIN PlantAttribute pa
ON p.PlantID = pa.PlantID AND pa.AttributeID = 1
INNER JOIN PlantAttribute pa2
ON p.PlantID = pa2.PlantID AND pa2.AttributeID = 2;
select * from Plants p where 2 = (
select count(*) from HasPlants h
where h.pid = p.id and h.aid in ( a2, a3 )
)