如何在我的SQL查询中使用COUNT

时间:2012-10-31 11:59:00

标签: sql count

我正在尝试计算product_id的出现次数。 这是我的查询返回10个产品,但不是根据product_id的出现次数。

SELECT name, category_id, product_id 
FROM product, notification 
WHERE type='product_consumed' OR type='product_rate' AND product.id = notification.product_id AND category_id="1" 
GROUP BY product_id ORDER BY product.category_id ASC LIMIT 10

我试着像这样计算product_id的出现次数,但它会给我带来不好的结果,

SELECT name, category_id, product_id, COUNT(*) AS most_viewed 
FROM product, notification 
WHERE type='product_consumed' OR type='product_rate' AND product.id = notification.product_id AND category_id=".$cat." 
GROUP BY product_id ORDER BY product.category_id ASC, most_viewed DESC LIMIT 10

我希望有这样的SQL响应:

产品类别|产品名称|观看次数

由于

1 个答案:

答案 0 :(得分:1)

试试这个,你缺少一组括号

SELECT name, category_id, product_id, COUNT(*) AS most_viewed 
FROM product, notification 
WHERE (type='product_consumed' OR type='product_rate') AND product.id = notification.product_id AND category_id=".$cat." 
GROUP BY product_id 
ORDER BY product.category_id ASC, most_viewed DESC LIMIT 10