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

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.custid是未知的:

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;

最佳答案

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

否则,您可以在子查询(在整个表中,而不是每行)中进行汇总计算,然后将子查询的结果与地址表联接起来以获取额外的数据。试试这个:

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 ...

09-05 02:14