基于多表选择的mysql更新查询

vh0rcniy  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(287)

请帮帮我。我有三张table:
用户id等级
文章id\u评级id\u作者
照片id\照片分级id\用户
需要根据公式查询更新用户评分:avg(用户帖子评分)+avg(用户照片评分)。尝试这一点,但只有当用户有和职位和照片。如果用户有照片,但没有帖子,则评分变为0:

UPDATE users U
                inner JOIN
                 (select id_user, avg(rating) as avgrating
                    from photos P
                    group by id_user
                 ) P
                 on U.id = P.id_user
               inner JOIN
                 (select author_id, avg(rating) as avgrating_posts
                  from posts PS
                    group by author_id
                 ) PS
                 on U.id = PS.author_id
                SET
        U.rating = (
                                            P.avgrating +
                                            PS.avgrating_posts 
                                         )

UPDATE users SET
        rating = (
            ( SELECT AVG(rating) FROM photos
                        WHERE photos.id_user = users.id AND deleted = 0 AND hidden = 0 AND date_published > 0 ) +
            ( SELECT AVG(rating) FROM posts
                        WHERE posts.author_id = users.id AND published_at > 0

) )

yx2lnoni

yx2lnoni1#

使用 left join用于内部查询,因此如果没有为用户找到关联的记录,则将返回null值。

UPDATE users U 
       LEFT JOIN (SELECT author_id, 
                          AVG(rating) AS avgrating_posts 
                   FROM   posts PS 
                   GROUP  BY author_id) PS 
               ON U.id = PS.author_id 
       LEFT JOIN (SELECT id_user, 
                          AVG(rating) AS avgrating 
                   FROM   photos P 
                   GROUP  BY id_user) P 
               ON U.id = P.id_user 
SET    U.rating =  COALESCE(P.avgrating,0) + COALESCE(PS.avgrating_posts,0)

相关问题