[英]How to query a many-to-many relationship
3 表: Fruits(id, name) Buckets(id, name) Bucket_Fruit(id, fruit_id, bucket_id, count)
例如有一个桶 Bucket1 有 2 个苹果和 1 个香蕉:
水果.id | 水果名称 |
---|---|
1 | 苹果 |
2 | 香蕉 |
桶.id | Buckets.name |
---|---|
1 | 桶 1 |
Bucket_Fruit.id | Bucket_Fruit.fruit_id | Bucket_Fruit.bucket_id | Bucket_Fruit.count |
---|---|---|---|
1 | 1 | 1 | 2 |
2 | 2 | 1 | 1 |
问题是:如何查询只有 2 个苹果和 1 个香蕉的桶? 我可以保证不会有 2 个桶有相同的水果。
尝试这个:
select distinct bucket_id
from Bucket_Fruit b
where exists (select * from Bucket_Fruit where bucket_id=b.bucket_id
and fruit_id=(select id from Fruits where name='apple')
and count=2)
and exists (select * from Bucket_Fruit where bucket_id=b.bucket_id
and fruit_id=(select id from Fruits where name='banana')
and count=1)
and bucket_id in (select bucket_id from Bucket_Fruit group by bucket_id having count(fruit_id)=2)
;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.