我收到了这个问题:
SELECT r.name, date(r.join_date) as join_date,
(COUNT(DISTINCT a.id) + COUNT(DISTINCT n.id)) as num_likes,
COALESCE(SUM(rv.views), 0) as sum_views
FROM restaurants r
LEFT JOIN apple_likes a ON r.id = a.restaurant_id
LEFT JOIN android_likes n ON r.id = n.restaurant_id
LEFT JOIN restaurant_views rv on r.id = rv.restaurant_id
WHERE r.id=192
GROUP BY r.id DESC
以下是另一个使用 num_like 变量并删除LEFT JOIN的查询:
SELECT r.name, date(r.join_date) as join_date,
COALESCE(SUM(rv.views), 0) as sum_views
FROM restaurants r
LEFT JOIN restaurant_views rv on r.id = rv.restaurant_id
WHERE r.id=192
GROUP BY r.id DESC
如您所见, sum_views更改为1793 ,这是正确的!
这意味着,当我删除其他LEFT JOIN时,sum_views显示正确的值
如何使上部查询在sum_views上显示正确的值?
(如果需要,我可以上传其他表格结构的图片!)
修改
我找到了一种使用子查询来解决问题的方法
SELECT r.name, date(r.join_date) as join_date,
(COUNT(DISTINCT a.id) + COUNT(DISTINCT n.id)) as num_likes,
(SELECT COALESCE(SUM(views), 0) FROM restaurant_views WHERE restaurant_id=192) as sum_views
FROM restaurants r
LEFT JOIN apple_likes a ON r.id = a.restaurant_id
LEFT JOIN android_likes n ON r.id = n.restaurant_id
WHERE r.id=192
GROUP BY r.id DESC
如果有人知道如何在不使用子查询的情况下解决这个问题,我很乐意听到它!
答案 0 :(得分:1)
您的join
正在乘以行数。一种解决方案是在连接之前预先聚合数据:
SELECT r.name, date(r.join_date) as join_date,
(coalesce(a.cnt, 0) + coalesce(n.cnt, 0)) as num_likes,
COALESCE(SUM(rv.views), 0) as sum_views
FROM restaurants r LEFT JOIN
(select a.restaurant_id, count(*) as cnt
from apple_likes a
group by a.restaurant_id
) a
ON r.id = a.restaurant_id LEFT JOIN
(select n.restuarant_id, count(*) as cnt
from android_likes n
group by n.restaurant_id
) n
ON r.id = n.restaurant_id LEFT JOIN
(select rv.restaurant_id, count(*) as cnt
from restaurant_views rv
group by rv.restaurant_id
) rv
on r.id = rv.restaurant_id
WHERE r.id = 192
GROUP BY r.id DESC
答案 1 :(得分:0)
所以试试:
SELECT r.name, date(r.join_date) as join_date,
(COUNT(DISTINCT a.id) + COUNT(DISTINCT n.id)) as num_likes,
COALESCE(SUM(rv.views), 0) as sum_views
FROM restaurants r
LEFT JOIN apple_likes a ON r.id = a.restaurant_id
LEFT JOIN android_likes n ON r.id = n.restaurant_id
INNER JOIN restaurant_views rv on r.id = rv.restaurant_id
WHERE r.id=192
GROUP BY r.id DESC;
答案 2 :(得分:0)
使用此:
SELECT r.name, date(r.join_date) as join_date,
(COUNT(DISTINCT a.id) + COUNT(DISTINCT n.id)) as num_likes,
COALESCE(SUM(rv.views), 0) as sum_views
FROM restaurants r
JOIN apple_likes a ON r.id = a.restaurant_id
JOIN android_likes n ON r.id = n.restaurant_id
JOIN restaurant_views rv on r.id = rv.restaurant_id
WHERE r.id=192
GROUP BY r.id DESC;
请注意,我只删除关键字left
,因此将其设为natural join
,以便在计算所有null joins
时不会包含该项。