2017-07-20 206 views
0

我只想獲取此類別中具有子類別或產品的類別。所以不應該顯示空的類別。MySQL僅選擇擁有子類別或子類別的類別

這是我最後一次嘗試:

SELECT * 
     FROM categories as c 
     WHERE c.parent = '3' # dynamic $id 
     AND c.visible = 'yes' 
     AND (
       (
        SELECT count(*) 
        FROM products 
        WHERE products.categorie = c.id 
       ) > 0 
       OR 
       (
        SELECT count(*) 
        FROM categories as b 
        #WHERE b.parent = c.id 
       ) > 0 
      ) 
     ORDER BY position DESC, `name` ASC 

categories.id從類別表的主鍵。
categories.parent包含來自父分類的id (primary key)
products.categorie包含id (primary key)作爲其父類別。
categories.visible是手動設置的屬性,可以忽略。

預先感謝您

回答

0

這是解決方案:

SELECT categories.* 
FROM categories 
WHERE categories.parent = '1' 
AND categories.visible = 'yes' 
AND (
     (SELECT count(*) FROM products WHERE products.categorie = categories.id AND visible = 'yes') > 0 
     OR 
     (SELECT count(*) FROM categories as sub WHERE sub.parent = categories.id) > 0 
    ) 
ORDER BY `position` DESC, `name` ASC;