Mysql
 sql >> Database >  >> RDS >> Mysql

SUM() non funziona in MySQL:SUM() con DISTINCT

Metti DISTINCT IN sum( rating.rating) as total_rating, ecco perché il risultato(12=17-5 ), poiché includerà 5 solo una volta durante il calcolo della somma.

 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

Ecco SQLFiddle

Esempio di output: Spero che questo aiuti