具有多个条件的Mysql查询

时间:2014-03-19 11:24:53

标签: mysql sql prestashop

我必须获得多个类别的产品(Prestashop数据库)。

我的查询:

SELECT COUNT( cp.`id_product` ) AS total
FROM  `ps_product` p
INNER JOIN ps_product_shop product_shop ON ( product_shop.id_product = p.id_product
AND product_shop.id_shop =1 ) 
LEFT JOIN  `ps_category_product` cp ON p.`id_product` = cp.`id_product` 
WHERE cp.`id_category` =6
AND cp.`id_category` =126
AND product_shop.`visibility` 
IN (
"both",  "catalog"
)
AND product_shop.`active` =1

我想在类别126内选择6类内部,但我的查询返回0。

产品可以有多个类别,因此我只想选择产品是否在两个类别中。

如何修复,所以我得到了预期的结果?

4 个答案:

答案 0 :(得分:2)

SELECT COUNT( cp.id_product ) AS total
FROM  ps_product p
Left JOIN ps_product_shop product_shop ON ( product_shop.id_product = p.id_product
                                            AND product_shop.id_shop =1 ) 
LEFT JOIN  ps_category_product cp ON p.id_product = cp.id_product 
WHERE cp.id_category in(6,126)
    AND product_shop.visibility IN ('both',  'catalog')
    AND product_shop.active =1

朋友试试这个,

SELECT COUNT( cp.id_product ) AS total
FROM  ps_product p
Left JOIN ps_product_shop product_shop ON ( product_shop.id_product = p.id_product
                                            AND product_shop.id_shop =1 ) 
LEFT JOIN  ps_category_product cp ON p.id_product = cp.id_product 
            and cp.id_category in(6)
LEFT JOIN  ps_category_product cp1 ON p.id_product = cp1.id_product 
            and cp1.id_category in(126)
WHERE cp.id_category is not null
    and cp1.id_category is not null
    AND product_shop.visibility IN ('both',  'catalog')
    AND product_shop.active =1

答案 1 :(得分:0)

使用

WHERE cp.`id_category` =6
OR cp.`id_category` =126

答案 2 :(得分:0)

你的意思是6到126之间?对于6和126都不能对一列进行验证。如果介于两者之间则使用,

SELECT COUNT( cp.`id_product` ) AS total
FROM  `ps_product` p
INNER JOIN ps_product_shop product_shop ON ( product_shop.id_product = p.id_product
AND product_shop.id_shop =1 ) 
LEFT JOIN  `ps_category_product` cp ON p.`id_product` = cp.`id_product` 
WHERE cp.`id_category` between 6 and 126
AND product_shop.`visibility` 
IN (
"both",  "catalog"
)
AND product_shop.`active` =1

答案 3 :(得分:0)

WHERE (cp.`id_category` = 6 OR cp.`id_category` = 126)
AND product_shop.`visibility` IN ("both",  "catalog")
AND product_shop.`active` = 1

在两个类别中:

SELECT COUNT( cp.id_product ) AS total
FROM  ps_product p
Left JOIN ps_product_shop product_shop ON (product_shop.id_product = p.id_product
                                           AND product_shop.id_shop = 1)     
WHERE product_shop.visibility IN ('both',  'catalog')
  AND product_shop.active = 1
  AND EXISTS(SELECT * FROM ps_category_product cp 
             WHERE p.id_product = cp.id_product AND cp.id_category = 6)
  AND EXISTS(SELECT * FROM ps_category_product cp 
             WHERE p.id_product = cp.id_product AND cp.id_category = 12)