连接更多表时聚合函数返回错误的值 [英] Aggregate functions return wrong values when joining more tables

查看:61
本文介绍了连接更多表时聚合函数返回错误的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要显示所有客户及其地址以及他们的订单数量和总金额。我的查询如下所示:

select *, sum(o.tota), count(o.total) 
from customer c 
natural join orders o
group by c.custId;

哪个工作正常。

但如果我向查询中添加一个新表:

select *, sum(o.tota), count(o.total) 
from customer c 
natural join orders o
natural join cust_addresses a
group by c.custId;

那么它将不再起作用。聚合函数返回错误的值,因为每个客户可能有多个地址,这是正确的,我还想显示它们的所有地址。 我可以做些什么来解决聚合函数问题?

我可以考虑这样做:

select *, (select total from orders o where o.custid=c.custid), ..
from customer c 
natural join orders o
natural join cust_addresses a
group by c.custId;

但这非常慢。

编辑 我现在尝试了以下方法,但它告诉我域c.cutid未知:

select *
from
     customer c,               
     left join (select sum(o.tota), count(o.total) from orders o where o.custid=c.custid) as o
where ...
group by c.custId;

推荐答案

简单解决方案:使用两个查询。

否则,您可以在子查询(针对整个表,而不是每行)中进行聚合计算,然后将子查询的结果与Addresses表连接以获得额外数据。试试这个:

SELECT *
FROM customer T1
LEFT JOIN
(
    SELECT custId,
           SUM(total) AS sum_total,
           COUNT(total) AS count_total
    FROM orders
    -- WHERE ...
    GROUP BY custId
) T2
ON T1.custId = T2.custId
-- WHERE ...

这篇关于连接更多表时聚合函数返回错误的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆