douwei1128 2014-01-26 19:11
浏览 106
已采纳

如何使用SUM并返回所有行,即使没有任何总和?

I have a table USERS and a table ORDERS. In my backend office I'm attempting to output a table with all users (customers) and SUM their individual order total, so to simplify I'm saying:

SELECT users.id, SUM(orders.total) as spent FROM users
    JOIN orders ON users.id=orders.customer_id GROUP BY users.id

(Note: do not pay attention to the syntax, this is just to illustrate the point. the syntax is fine when I run it.)

I now have say 4 users in total and the ORDERS table looks something like this:

order_id  customer_id  total
1         1            25
2         2            10
3         1            5   

Then my query will output ONLY those users that can be found in the ORDERS table and my backend customer overview table will look unfortunately like this:

Customer ID      Spent in Total
1                30
2                10

ignoring completely the other 2 users who have not yet placed any orders. What I want to see is this:

Customer ID      Spent in Total
1                30
2                10
3                0
4                0

Is there a way to do this?

My guess is that it has something to do with special joins like inner, outer, but I don't know the difference there.

Also what I thought about was to run two queries, selecting * from users and then running a foreach to sum up order total, but this seems inefficient.

  • 写回答

3条回答 默认 最新

  • drus40229 2014-01-26 19:14
    关注

    You need a left join, and on some (old) versions of MySQL also an IFNULL().

    SELECT 
      users.id, 
      IFNULL(SUM(orders.total),0) as spent 
    FROM users
    LEFT JOIN orders ON users.id=orders.customer_id 
    GROUP BY users.id
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 找人不需要人工智能回答的gamit解算后做形变分析
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错