我有4个表,分别是商店,用户,评论和评级。
我希望获得相应商店的所有评论,其中包含已审核的用户详细信息以及该商店的整体评分。
我几乎完成了单一查询。但问题是,如果商店对同一用户进行多次相同评级,则将其视为单一评级。但那个评级数是正确的。
即
从该表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
当我运行此查询时,我得到了
但是对于user_id 3,我需要total_rating 17 ..
选中此fiddle
答案 0 :(得分:3)
您将DISTINCT
置于sum( rating.rating) as 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
答案 1 :(得分:2)
尝试此操作 - 从sum(rating.rating)
中删除不同内容。由于您提供了sum(distinct rating.rating)
,因此忽略了用户3为商店1提供的5个。
select review.comments, users.username, 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
答案 2 :(得分:2)
首先:从表中外连接记录然后在WHERE子句中删除它们是没有意义的。使用left join review ...
,您可以说:在表查看中找到匹配的记录,如果找不到,则添加空值,以便我们保留用户记录。然后使用where review.shop_id='1'
说:只记录您实际在审核中找到记录的记录。所以你要解雇那些你只是痛苦不堪的记录。你的WHERE子句使你的LEFT OUTER加入仅仅INNER JOINS。
关于你的实际问题:这源于首先加入所有表,然后尝试从结果记录中获取聚合。在加入之前聚合:
select
rev.comments,
usr.username,
coalesce(rat.rating_count, 0) as rating_count,
rat.total_rating
from review rev
join users usr on users.id = review.user_id
left join
(
select user_id, shop_id, count(*) as rating_count, sum(rating) as total_rating
from rating
group by user_id, shop_id
) rat on rat.user_id = usr.id and rat.shop_id = rev.shop_id
where rev.shop_id = 1
group by rev.id;