如何从两个关联表按多条件匹配多行获取对应数据



问题描述
我编写了如下SQL查询两个关联表的数据:
SELECT product.xid as xid, product.option_group_id as option_group_id, product.brand_id as brand_id FROM product_promotion as product LEFT JOIN product_promotion_to_filters as filters ON(filters.product_xid = product.xid) WHERE (filters.options_xid = '04320095' and filters.value_xid = '50073608') and (filters.options_xid = '85047331' and filters.value_xid = '77933356')
查询返回空结果,问题出在WHERE条件部分:两个条件对应不同行的记录,单一行无法同时满足两个AND关联的条件。
我需要在查询中同时匹配多个行级过滤条件,只返回满足所有指定条件的记录,比如上述查询我只想要获取xid为27145569的符合所有条件的数据,有时需要匹配的条件可能有2-3个甚至更多。
解决方案
找到的可行写法如下:
WHERE CONCAT(filters.options_xid,filters.value_xid) IN ('0432009550073608', '8504733163299671') HAVING COUNT(product.xid) >= 2;
内容的提问来源于stack exchange,提问作者Faber Aksel
相关产品推荐
相关产品推荐

