SQL Sum and Count JOIN 多个表

SQL Sum and Count JOIN Multiple tables

请帮忙,我想合并这两个查询

我有 3 个表(地点,评分,places_image)

地点

评分

places_image

这是 2 个查询:

SELECT places.*, SUM(rating) AS total_rating,COUNT(ratings.user_id) AS total_user FROM ratings, places WHERE ratings.place_id = places.id GROUP BY places.id
SELECT places.*, places_images.image FROM places, places_images WHERE places.id = places_images.place_id GROUP BY places.id

查询 1

查询 2

我尝试执行此查询,但它为 聚合 函数

提供了重复数据
SELECT places.id, places.name, places.description, places_images.image ,SUM(rating) AS total_rating,COUNT(ratings.user_id) AS total_user FROM places_images JOIN places ON places_images.place_id = places.id JOIN ratings ON ratings.place_id = places.id GROUP BY places.id

查询 3

我该如何合并它?

您需要在 place_id 和 user_id

上使用 2 Inner Join

会是这样的

SELECT SUM(r.rating) AS total_ratings, COUNT(r.user_id) AS total_users
FROM ratings r 
INNER JOIN places p ON p.id = r.user_id 
INNER JOIN places_image pi ON pi.place_id = r.place_id    
GROUP BY r.id

看来我唯一需要的就是对其进行子查询

select a.*, d.image, b.totalRating, c.totalUser from places a, ( select place_id, sum(rating) AS totalRating from ratings group by place_id ) b, ( select place_id, count(id) AS totalUser from ratings group by place_id ) c, places_images d where c.place_id = a.id and b.place_id = a.id and d.place_id = a.id GROUP BY a.id

Result

非常感谢,GBU