SQL查询 - 在一个产品上放置多个条件

时间:2011-10-19 10:41:15

标签: mysql sql innodb

请帮我解决这个问题: 我有一张表:

id_feature  id_product  id_feature_value
1              1           50
2              1           54
5              1           67

我想从这张表中选择:

table中选择计数(id_product),其中(id_feature = 1 AND id_feature_value = 50)AND(id_feature = 2 AND id_feature_value = 54)AND(id_feature = 5 AND id_feature_value = 67)

我的查询必须符合条件。喜欢有计数(条件)= 3

我不知道怎么写这个!

请帮帮我!抱歉我的英文!

    SELECT count( pf.id_product ) AS nr_product, value, fv.id_feature_value, filter
FROM `nk_category_features` cat_f
INNER JOIN `nk_feature_value` fv ON fv.id_feature = '11'
AND fv.value IS NOT NULL
INNER JOIN `nk_product_features` pf ON pf.id_feature = '11'
AND pf.id_feature_value = fv.id_feature_value
INNER JOIN `nk_product` p ON p.id_product = pf.id_product
AND p.product_active = '1'
INNER JOIN `nk_product_features` pf1 ON ( pf1.id_feature = '14'
AND (
pf1.id_feature_value = '21'
) )
WHERE cat_f.id_feature = '11'
AND filter >0
GROUP BY pf.id_feature, pf.id_product
ORDER BY abs( fv.value ) ASC

这是我现在使用的查询,但我不喜欢解决方案宽度内连接,内联接在同一个表上

1 个答案:

答案 0 :(得分:4)

试试这个:

select id_product,count(*)
from table
where (id_feature = 1 AND id_feature_value = 50) 
   OR (id_feature = 2 AND id_feature_value = 54) 
   OR (id_feature = 5 AND id_feature_value = 67)
group by id_product
having count(*) = 3

获得符合where子句的产品总数

select count(*)
from 
  ( select id_product
    from table
    where (id_feature = 1 AND id_feature_value = 50) 
       OR (id_feature = 2 AND id_feature_value = 54) 
       OR (id_feature = 5 AND id_feature_value = 67)
    group by id_product
    having count(*) = 3
  ) tmp