MySQL总和加上同一查询中的计数

时间:2013-12-19 14:47:08

标签: mysql sql rating rate

我正在尝试从匿名人员和已注册的人那里获得费率。他们在不同的表格中。

SELECT product.id, (SUM( users.rate + anonymous.rate ) / COUNT( users.rate + anonymous.rate ))
FROM products AS product
LEFT JOIN users ON users.id_product = product.id
LEFT JOIN anonymous ON anonymous.id_product = product.id
GROUP BY product.id
ORDER BY product.date DESC 

因此,表格如下:

users-->
id | rate | id_product | id_user
1     2        2           1
2     4        1           1
3     5        2           2

anonymous-->
id | rate | id_product | ip
1     2        2          192..etc
2     4        1          198..etc
3     5        2          201..etc

我正在尝试查询的是:对于每种产品,我希望得到平均费率。目前输出为null,但我在两个表中都有值。

感谢。

3 个答案:

答案 0 :(得分:1)

试试这样..

SELECT product.id, (SUM( ifnull(ur.rate,0) + ifnull(ar.rate,0) ) / (COUNT(ur.rate)+Count(ar.rate)))
FROM products AS product
LEFT JOIN users_rate AS ur ON ur.id_product = product.id
LEFT JOIN anonymous_rate AS ar ON ar.id_product = product.id
GROUP BY product.id 

Sql Fiddle Demo

答案 1 :(得分:0)

首先,您将获得表中每个产品的交叉连接。这不是你真正想要的。我认为这接近你正在寻找的东西

SELECT p.id,
       (coalesce(u.sumrate, 0) + coalesce(a.sumrate, 0)) / coalesce(u.num, 0) + coalesce(a.num, 0))
FROM products p LEFT JOIN
     (select id_product, sum(rate) as sumrate, count(*) as num
      from users u
      group by id_product
     ) u
     ON u.id_product = p.id left join
     (select id_product, sum(rate) as sumrate, count(*) as num
      from anonymous a
      group by id_product
     ) a
     ON a.id_product = p.id
ORDER BY p.date DESC;

假设id在产品表中是唯一的,您不需要在外层进行聚合。

答案 2 :(得分:0)

如果按

分组,则不能对连接使用计数和求和
CREATE TABLE products (id integer);
CREATE TABLE users_rate (id integer, id_product integer, rate integer, id_user integer);
CREATE TABLE anonymous_rate (id integer, id_product integer, rate integer, ip varchar(25));

INSERT INTO products VALUES (1);
INSERT INTO products VALUES (2);
INSERT INTO products VALUES (3);
INSERT INTO products VALUES (4);

INSERT INTO users_rate VALUES(1, 1, 3, 1);
INSERT INTO users_rate VALUES(1, 2, 3, 1);
INSERT INTO users_rate VALUES(1, 3, 3, 1);
INSERT INTO users_rate VALUES(1, 4, 3, 1);

INSERT INTO anonymous_rate VALUES(1, 1, 3, '192..');
INSERT INTO anonymous_rate VALUES(1, 2, 3, '192..');

select p.id,
ifnull(
  ( ifnull( ( select sum( rate ) from users_rate where id_product = p.id ), 0 ) +
    ifnull( ( select sum( rate ) from anonymous_rate where id_product = p.id ), 0 ) )
  /
  ( ifnull( ( select count( rate ) from users_rate where id_product = p.id ), 0 ) +
    ifnull( ( select count( rate ) from anonymous_rate where id_product = p.id ), 0 )), 0   )
from products as p
group by p.id

http://sqlfiddle.com/#!2/a2add/8

我检查了sqlfiddle。当没有费率时给出0。你可以改变它。