0

I am trying to do a count query that requires a group by. But when I get my results I am getting the correct amount of rows but with their tally in the total column instead of the amount of rows which is what I want.

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 

What can I do to make it give me the total rows, instead of grouping the totals of each product ID as total.

Sample of what I am getting:

total
1
2
1
1
2
2

What I want:

total
6
4

3 回答 3

0

使用 ROLLUP

GROUP  BY p.products_id WITH ROLLUP;

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

GROUP  BY p.products_id, rollup(p.SOME_COLUMN);
于 2013-05-16T13:16:35.820 回答
0

将所有内容嵌套在子查询中:

SELECT COUNT(*) FROM (
      [your query here]
) AS subquery
于 2013-05-16T13:13:57.680 回答
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 函数或等效的 PDO mysql_num_rows()mysqli_num_rows()具体取决于您使用的 mysql 函数集。(不建议使用此选项,因为它对服务器有不必要的开销。)

于 2013-05-16T13:30:34.087 回答