我正试着从匿名者和注册者那里得到费用。它们在不同的桌子上。
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
我的问题是:对于每种产品,我都希望得到平均价格。当前输出为空,但两个表中都有值。
谢谢。
最佳答案
像这样试试。。
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
关于mysql - MySQL总和加上相同查询中的计数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20684656/