2014-03-19 73 views
-1

我必須獲得多個類別的產品(Prestashop數據庫)。使用倍數條件的Mysql查詢

這是我的查詢:

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 

我要選擇內6類和內126類,但我的查詢返回0

產品可以有數倍的類別,所以我只想選擇如果產品在兩個類別內。

這是如何解決的,所以我得到了預期的結果?

+0

insted的cp.id_category = 6 AND cp.id_category = 126。 (6,126)中使用cp.id_category。檢查下面的完整代碼。 – AK47

+0

內連接使用左連接 – AK47

回答

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 
+0

它返回類別6和類別126中的產品,但不是僅在這兩個類別內產品 –

+0

裏面是什麼意思?請舉例說明。 – AK47

+0

我在第6類有兩個產品。我有126類的3個產品。只有一個產品有類別6和126所以,我只需要1個結果! –

0

使用

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

不是。我只想要這些類別的產品,不是全部在類別6內,並且全部在內部類別126 –

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 
+0

不僅在類別6和126中 –

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)