MySql query over many-to-many relationship [duplicate]

别等时光非礼了梦想. 提交于 2019-12-11 02:35:31

问题


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?


回答1:


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;



回答2:


select * from Plants p where 2 = ( 
  select count(*) from HasPlants h
     where h.pid = p.id and h.aid in ( a2, a3 ) 
  )


来源:https://stackoverflow.com/questions/1202978/mysql-query-over-many-to-many-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!