使用group by计数,返回行数

时间:2013-05-16 13:09:31

标签: php mysql

我正在尝试进行需要分组的计数查询。但是当我得到我的结果时,我得到了正确的行数,但是它们在总列中的计数而不是我想要的行数。

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

3 个答案:

答案 0 :(得分:0)

将所有内容嵌入子查询中:

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

答案 1 :(得分:0)

Use ROLLUP

GROUP  BY p.products_id WITH ROLLUP;

编辑:我假设您使用的是MySQL。其他DBMS具有不同的语法:

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

答案 2 :(得分: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函数集。 (不建议使用此选项,因为服务器有不必要的开销。)