2011-07-15 42 views
0

我有一個表格結構如下,我想選擇 所有活動類別 與活動產品 一個特定的父母ID。正在最小化此類sql查詢所需的類別/產品關係?

因此,如果我插入特定的parentID,我只會獲取包含活動產品的父級的相關活動子類別。

這是我的sql(mysql)到目前爲止工作,但看起來很骯髒,爲了學術界的緣故,我想知道是否有更好的方法。在我看來,選擇所有activeID來過濾結果是有點浪費,但我無法想出辦法解決這個問題,還是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 
+0

一個很好的問題是「什麼是你better'的'定義是什麼?」更快(以秒爲單位),更少的資源(比如cpu週期),更易讀,更易維護/適應性強,代碼行少等。 – MatBailie

+0

更少的代碼行數,然後減少cpu週期。 cpu週期意味着更快嗎? – polyhedron

+0

如果您獲得並行性,請不要使用它。您可以使用2個核心(而不是1個),並節省25%的時間。總體而言,您使用的CPU時間爲150%,但佔實際時間的75%。 – MatBailie

回答

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

足夠接近完美的我。正是我在找的東西,我學到了一些關於如何使用INNER JOIN的內容 – polyhedron

相關問題