Mysql:SUM加入表值

时间:2017-05-25 14:52:46

标签: php mysql join sum

我遇到了加入问题和SUM()

我有两个表,agents(id, name)orders(id, agent_id, total)

现在,我需要一份所有代理商的清单,列出他们下达的订单数量和订单总数。这是我的基本查询:

SELECT
    agents.*,
    COUNT(DISTINCT orders.id) total_orders,
    SUM(orders.total) total_amount
FROM agents
LEFT JOIN orders ON agents.id = orders.agent_id
GROUP BY agents.id

total_orders是正确的,但total_amount不是。每个代理都有错误的SUM(),即使那些没有订购任何东西的人都有价值。

在一个查询中是否可以?我不想再循环查询。

1 个答案:

答案 0 :(得分:1)

您不需要左连接,请将LEFT JOIN替换为JOIN

SELECT
    agents.*,
    COUNT(DISTINCT orders.id) total_orders,
    SUM(orders.total) total_amount
FROM agents
JOIN orders ON agents.id = orders.agent_id
GROUP BY agents.id

您获得的错误结果是由于左连接将从 orders 表中检索一行这一事实,即使没有记录的agent_id等于to agents.id

另一方面,单个联接不会检索没有订单的代理。

哦,那么你需要所有代理人,并且对于那些没有订单的人来说总共需要0 ...然后左连接应该有效。否则你可以这样做:

SELECT
    agents.*,
    COUNT(DISTINCT orders.id) total_orders,
    SUM(CASE WHEN orders.id IS NULL then 0 ELSE orders.total END) total_amount
FROM agents
LEFT JOIN orders ON agents.id = orders.agent_id
GROUP BY agents.id
相关问题