最小化这个sql查询的类别/产品关系是否必要?

时间:2011-07-15 15:14:08

标签: mysql sql

我有一个表结构如下,我想选择 所有活跃的类别 与活跃的产品 特定父ID的。

因此,如果我插入特定的parentID,我只会获得包含活动产品的父级的相关活动子类别。

这是我的sql(mysql)到目前为止有效,但看起来很讨厌,为了学术界我想知道是否有更好的方法。在我看来,选择所有活动的产品ID来过滤结果是一种浪费,但我无法解决这个问题,或者mysql是否找到了处理此查询的最佳方法?

(many-to-many upon itself)
categories
----------
categoryID
parentID
name
isActive (bool)

(linker table between categories and product)
productCategories
-----------------
productID
categoryID

products
--------
productID
name
isActive (bool)


SELECT productCategories.categoryID, categories.* FROM productCategories
                LEFT JOIN categories ON
                    productCategories.categoryID = categories.categoryID
                WHERE 
                    productCategories.categoryID IN 
                    (SELECT categoryID FROM categories WHERE parentID = {$parentID} AND isActive = 1)
                    AND
                    productCategories.productID IN
                    (SELECT productID FROM products WHERE isActive = 1)
                GROUP BY productCategories.categoryID

1 个答案:

答案 0 :(得分:2)

另一种布局可能如下......

SELECT
  *
FROM
(
  SELECT
    productCategories.categoryID
  FROM
    productCategories
  INNER JOIN
    categories
      ON categories.categoryID = productCategories.parentID
  INNER JOIN
    products
      ON products.productID    = productCategories.productID
  WHERE 
    categories.parentID = {$parentID}
    AND categories.isActive = 1
    AND products.isActive = 1
  GROUP BY
    productCategories.categoryID
)
  AS category_map
LEFT JOIN
  categories AS [children]
    ON category_map.categoryID = categories.categoryID