assigned_features
feature_id | item_id
-----------------------------------------------
1 | 1
2 | 1
3 | 1
1 | 2
2 | 2
1 | 3
Using mysql, I'm trying to return all items which contain all selected features.
For example, I wish to return items where feature_id = 1 and 2. This should return item_id 1 and 2.
Alternatively, if I only wish to retrieve items where feature_id = 1,2 and 3, the result should yield item 1.
I don't really know where to begin.
Thank you!
You can do aggregation :
select item_id
from assigned_features af
where feature_id in (1,2)
group by item_id
having count(distinct feature_id) = 2;
In similarly you can just increment the count for second example :
select item_id
from assigned_features af
where feature_id in (1,2,3)
group by item_id
having count(distinct feature_id) = 3;
However, DISTINCT
is redundant here if item_id
doesn't have a duplicate feature_id
s then you can use count(*) = 2
or count(*) = 3
instead.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.