mysql distinct sum,SUM()在MySQL中不起作用:具有DISTINCT的SUM()

I have 4 tables called shops, users, review and rating.

I want to get all reviews for the corresponding shop with reviewed user details and also overall rating for that shop.

I have done almost with the single query. But the problem is if the shop has same rating for multiple times by same user its consider as single rating. But that rating count was correct.

i.e

c489edc563bece9f6e2d101f6b1a9c7e.png

from this table user_id 3 was rated shop_id 1 as 4 times. So the count is 4 and total_rating is 17.

My query is

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

When I run this query I got

390da796b99054e4f142a90ec8b66c31.png

But I need total_rating 17 for user_id 3..

Check this fiddle

解决方案

You put DISTINCT IN sum( rating.rating) as total_rating, thats why the result(12=17-5), since it will include 5 only once while computing sum.

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

Sample Output :

76193708844ce30481c7064a4ac9f974.png

Hope this helps

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值