2013-05-16 88 views
0

我正在嘗試做一個需要group by的count查詢。但是當我得到我的結果時,我得到了正確數量的行,但他們的總數列中的計數,而不是我想要的行數量。用組數來計算,返回行數

SELECT Count(p.products_id) AS total 
FROM products p 
     LEFT JOIN specials s 
       ON p.products_id = s.products_id 
     LEFT JOIN manufacturers m 
       ON p.manufacturers_id = m.manufacturers_id 
     JOIN products_description pd 
     ON p.products_id = pd.products_id 
     JOIN products_to_categories p2c 
     ON p.products_id = p2c.products_id 
     INNER JOIN products_specifications ps7 
       ON p.products_id = ps7.products_id 
     LEFT JOIN products_to_icon p2i 
       ON p.products_id = p2i.products_id 
     LEFT JOIN products_icons pi 
       ON p2i.icons_id = pi.icons_id 
WHERE p.products_status = '1' 
     AND pd.language_id = '1' 
     AND ps7.specification IN ('Polycotton') 
     AND ps7.specifications_id = '7' 
     AND ps7.language_id = '1' 
GROUP BY p.products_id 

我能做些什麼來使它給我總行數,而不是將每個產品ID的總數分組爲總數。

什麼樣我得到的:

total 
1 
2 
1 
1 
2 
2 

我想要什麼:

total 
6 
+0

當前計數是否可以包含0?如果是這樣,總數應該包括那一行嗎? –

回答

0

選項1:

Count(t.products_id) AS total FROM (
    SELECT p.products_id 
    FROM products p 
      LEFT JOIN specials s 
        ON p.products_id = s.products_id 
      LEFT JOIN manufacturers m 
        ON p.manufacturers_id = m.manufacturers_id 
      JOIN products_description pd 
      ON p.products_id = pd.products_id 
      JOIN products_to_categories p2c 
      ON p.products_id = p2c.products_id 
      INNER JOIN products_specifications ps7 
        ON p.products_id = ps7.products_id 
      LEFT JOIN products_to_icon p2i 
        ON p.products_id = p2i.products_id 
      LEFT JOIN products_icons pi 
        ON p2i.icons_id = pi.icons_id 
    WHERE p.products_status = '1' 
      AND pd.language_id = '1' 
      AND ps7.specification IN ('Polycotton') 
      AND ps7.specifications_id = '7' 
      AND ps7.language_id = '1' 
    GROUP BY p.products_id 
)t 

這將包括行,首先將返回一個0 ...

如果你不希望出現這種情況,然後添加下GROUP BY線這條線:

HAVING count(p.products_id) > 0 

選項2: 只需使用php函數mysql_num_rows(),mysqli_num_rows()或PDO等效項,具體取決於您使用的是哪一組mysql函數。 (不建議使用此選項,因爲它對於服務器而言是不必要的開銷。)

+0

你說的這個「不必要的開銷」是什麼? – TML

+0

@TML option2中不必要的開銷是Mysql實際上將多行返回給PHP,因此PHP可以確定它有多少行。在選項1中,Mysql將只返回1行並且其中包含計數。 –

+0

我明白你的意思了;我把這個問題解釋爲他想要的是單獨的行和*行數。也許我誤解了。 – TML

0

巢一切都在一個子查詢:

SELECT COUNT(*) FROM (
     [your query here] 
) AS subquery 
0

Use ROLLUP

GROUP BY p.products_id WITH ROLLUP; 

編輯:我假設你正在使用MySQL。其他DBMS有不同的語法:

GROUP BY p.products_id, rollup(p.SOME_COLUMN); 
+0

這給了我這個:http://i.imgur.com/1oTOFUF.png – Sackling

+0

它將永遠是最後的結果,在你的情況下,9 ...可以肯定,你應該選擇另一列'SELECT p.products_id ,COUNT(p.products_id)'。然後列p.products_id將爲NULL。試試吧...... –