gpt4 book ai didi

mysql - 多个 LEFT JOIN - 输出错误

转载 作者:行者123 更新时间:2023-11-29 12:23:31 25 4
gpt4 key购买 nike

我收到这个查询:

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

enter image description here

这是另一个查询,其中删除了 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

enter image description here

如您所见,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

如果有人知道如何在不使用子查询的情况下解决这个问题,我很有兴趣听到它!

最佳答案

您的连接正在乘以行数。一种解决方案是在连接之前预先聚合数据:

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

关于mysql - 多个 LEFT JOIN - 输出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28686460/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com