2012-01-17 56 views
0

我有一個查詢,我想優化。我確信這個查詢可以改進。mysql鏈接表+加入+數

查詢的結果應該返回具有filter_id 22和2並且顯示'yes'的產品的數量。

SELECT COUNT(product_id) AS Total 
FROM kkx_filters_products 
    LEFT JOIN kkx_products ON product_id = kkx_products.id 
WHERE filter_id IN (2,22) 
    AND kkx_products.display = 'yes' 
GROUP BY product_id 
HAVING count(product_id) = 2 

上述查詢返回每個記錄10230與外地達爾和值2
我想一個結果與現場總與價值10230.

我已經包含的結構查詢中使用的表。

EXPLAIN kkx_filters;

Field   Type     Null Key  Default  Extra 
id    int(11) unsigned  NO PRI  NULL   auto_increment 
name    varchar(50)   NO    

EXPLAIN kkx_filters_products;

Field   Type     Null Key Default   Extra 
filter_id  int(11)    NO PRI 0  
product_id  int(11)    NO PRI 0 

EXPLAIN kkx_products;

Field   Type     Null Key Default   Extra 
id    int(11)    NO PRI NULL    auto_increment 
title   varchar(255)   NO    
display   enum('yes','no')  NO   yes  
+0

'...作爲行的計數...一個結果與結果'...呵呵? – 2012-01-17 14:47:05

+0

*「應該返回具有filter_id 22 **和** 2的產品的數量」*但「HAVING count(product_id)= 1」表示22 **或** 2.這是什麼原因? – 2012-01-17 14:51:03

+0

抱歉,由於缺乏清晰度,我更清楚地闡述了我的問題 – 2012-01-17 21:14:47

回答

0

你可以換你的查詢有:

SELECT COUNT(*) 
FROM 
    (yourquery) AS tmp 

,但它不會是非常有效的。相反,加入產品表到過濾器表兩次:

SELECT 
     COUNT(*) AS Total 
FROM 
     kkx_products AS p 
    JOIN 
     kkx_filters_products AS f1 
    ON f1.product_id = p.id 
    AND f1.filter_id = 2 
    JOIN 
     kkx_filters_products AS f2 
    ON f2.product_id = p.id 
    AND f2.filter_id = 22 
WHERE 
     p.display = 'yes'