mysql - How to only include result if all related values exist in input list -
i've got object product
has many tag
s. want write query that, given list of tag
ids, returns product
if product's tags included in input list. input list may have tag ids not part of product, that's ok, product can still returned (i.e. of product's tags must exist subset of input list included in result).
i able write 1 query accomplish this, i'd able without sub-query in join. i've got:
select * product left join product_tag on product_tag.product_id = product.id left join ( select product.id, count(*) record_count product left join product_tag on product_tag.product_id = product.id group product.id ) inner_q on inner_q.id = product.id product_tag.id in (1, 2, 3) -- sample tag ids group product.id having count(*) = inner_q.record_count
does required result?
select * product id in (select product_id product_tag group product_id having sum(case when id in (1, 2, 3) 1 else 0 end) >= 3)
Comments
Post a Comment