php - SUM() 在 MySQL : SUM() with DISTINCT 中不起作用

标签 php mysql

我有 4 个表,分别是商店、用户、评论和评级。

我想获取相应商店的所有评论以及评论的用户详细信息以及该商店的总体评分。

我几乎完成了单个查询。但问题是,如果同一用户多次对商店进行相同评级,则将其视为单一评级。但该评分计数是正确的。

enter image description here

从这个表中,user_id 3 被评为 shop_id 1 4 次。所以计数是 4,total_rating 是 17。

我的查询是

select review.comments, users.username, count(distinct rating.id) as rating_count,
sum(distinct rating.rating) as total_rating from users 
left join review on users.id = review.user_id and review.shop_id='1' 
left join rating on users.id = rating.user_id and rating.shop_id='1' 
where review.shop_id='1' or rating.shop_id='1' 
group by users.id, review.user_id, rating.user_id, review.id

当我运行这个查询时,我得到了

enter image description here

但我需要 user_id 3 的 total_rating 17..

检查这个fiddle

最佳答案

您将 DISTINCT IN sum( rating.rating) 作为 total_rating, 这就是结果 (12=17-5) 的原因,因为计算总和时只会包含一次 5。

 select review.comments, review.user_id, count(distinct rating.id) as rating_count,
    sum( rating.rating) as total_rating from users 
    left join review on users.id = review.user_id and review.shop_id='1' 
    left join rating on users.id = rating.user_id and rating.shop_id='1' 
    where review.shop_id='1' or rating.shop_id='1' 
    group by users.id, review.user_id, rating.user_id, review.id

这里是 SQLFiddle

示例输出: enter image description here 希望这有帮助

关于php - SUM() 在 MySQL : SUM() with DISTINCT 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33667657/

相关文章:

验证用户名时的 PHP 错误

PHP - 在数据库问题中编辑数据

javascript - 如何延迟发送 ajax 请求?

php - 如何对齐动态生成的 div 或段落

php - fopen 有一些奇怪的行为

mysql - 当另一个事务拥有排他锁时,MySQL 如何允许获取共享锁?

sql - ORDER BY 条件

php - mysqli_affected_rows() 返回 -1 但查询有效

php - 是否应该在数据库级别处理唯一字段的验证?

mysql - SQL中的主键长度