如果特定列具有两个值,如何从数据库中获取ID

时间:2014-02-10 10:00:40

标签: mysql sql between zen-cart having-clause

数据库列,现在我想获得那些具有OPTIONS_VALUES_ID(12和31)的产品ID

Database Image

  SELECT DISTINCT  pa.products_id,options_values_id,options_id , COUNT(options_values_id) FROM products_attributes pa WHERE 
            pa.products_id IN (3331,3452,3455) AND pa.options_values_id IN (12,31) 
            GROUP BY pa.products_id
            HAVING (pa.options_values_id) >  0

以上查询结果 Above Query Result

我无法弄清楚如何只获取用户>定义 options_value_id 产品ID

2 个答案:

答案 0 :(得分:2)

我认为这就是你的意思......

SELECT products_id,COUNT(options_values_id) 
FROM products_attributes WHERE 
options_values_id in(12,31)
GROUP BY products_id
having COUNT(options_values_id)>=2

SQLFiddle

答案 1 :(得分:0)

无需使用DISTINCT,因为GROUP BY会删除pa.products_id的重复值

SELECT pa.products_id,options_values_id,options_id , COUNT(options_values_id) 
FROM products_attributes pa 
WHERE pa.options_values_id IN (12,31) 
GROUP BY pa.products_id

希望这会对你有帮助......!