mysql查询多对多查询_MySQL查询多对多关系

bd96500e110b49cbb3cd949968f18be7.png

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?

解决方案

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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值