【问题标题】:Use mysql joins to count no of invoices of customers使用 mysql joins 统计客户的发票数量
【发布时间】:2018-09-02 00:34:49
【问题描述】:

我的invoices 表有orderId 列,这是一个引用orderId primary key column of orders table 的外键,而订单表有customerId 列,它引用了客户表的customerId 主键列。 一个客户可以有多个订单,但一个订单只有一张发票。

我想计算每个客户的发票数量。以下是我尝试过的查询:

SELECT customers.name, COUNT(*) as number_of_invoices 
FROM invoices 
JOIN orders 
ON invoices.orderId = orders.orderId 
JOIN customers 
ON orders.customerId = customers.customerId;

但它只返回一个客户,并且计数是该客户的总计数而不是发票计数。

【问题讨论】:

  • 你需要在最后加上GROUP BY customers.name
  • @Brainy Prb 如果你觉得这个解决方案有用,那么请接受我的回答。

标签: mysql sql database join


【解决方案1】:

如果您只需要知道每个客户的发票数量。不用JOIN 也可以完成。由于订单和发票具有一对一的映射关系,您可以使用下面的 sql 查询

select customerId ,count(orderId) as invoice_count from orders group by customerId

【讨论】:

  • 很好,但我也需要客户的姓名,所以加入是强制性的吧?
  • 不,您也可以使用内联查询。我讨厌JOIN :)。内联查询更具可读性。
  • 不过,如果您想使用JOIN,您只能使用两个表订单和客户来实现此目的。除非您需要发票表中的任何列,否则您不需要发票。
【解决方案2】:

以下是您的问题的解决方案:

SELECT customers.name, COUNT(*) as number_of_invoices 
FROM invoices 
INNER JOIN orders 
ON invoices.orderId = orders.orderId 
INNER JOIN customers 
ON orders.customerId = customers.customerId
GROUP BY Customers.name;

只需在您的查询中最后添加GROUP BY 即可对每个客户的发票计数进行分组。

【讨论】:

    猜你喜欢
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多