MySQL 使用 JOIN 计数多个表

MySQL COUNT multiple tables with JOIN

我在尝试使用连接 select 多个表的总数时遇到问题。 COUNT的结果不正确。

我有三个表:

Customers
id -> Primary/Autoincrement
name

Documents
id -> Primary/Autoincrement
customer_id

Documents_items
id -> Primary/Autoincrement
document_id

我想获得按客户名称分组的文档和文档项的总数。

    SELECT cust.name, 
           COUNT(doc.id), 
           COUNT(item.id)
      FROM customers AS cust
INNER JOIN documents AS doc ON doc.customer_id = cust.id
INNER JOIN documents_items AS item ON item.document_id = doc.id
  GROUP BY cust.name

问题是 COUNT(doc.id) 的结果等于 COUNT(item.id) 的结果,这是不正确的。

您可以在 SQLFiddle.

中查看错误的演示示例

输入示例:

INSERT INTO customers VALUES('John')
INSERT INTO documents VALUES(1)
INSERT INTO documents_items VALUES(1), VALUES(1)

预期输出

Name     |    Total Docs    | Total Items
John              1               2

当前输出:

Name     |    Total Docs    | Total Items
John              2               2

试试这个方法:

SELECT T1.name,T1.Docs,T2.Items
FROM 
( SELECT cust.name, COUNT(doc.id) as Docs
  FROM customers AS cust
  INNER JOIN documents AS doc ON doc.customer_id = cust.id
  GROUP BY cust.name) T1 JOIN

( SELECT cust.name, COUNT(item.id) as Items
  FROM customers AS cust
  INNER JOIN documents AS doc ON doc.customer_id = cust.id
  INNER JOIN documents_items AS item ON item.document_id = doc.id
  GROUP BY cust.name) ON T1.name =T2.name

解释:

您必须为每个计数生成两个结果。然后用名称字段加入这些结果。

第一个内部查询将生成文档的名称和计数。第二个内部查询将生成项目的名称和数量。然后我们将在名称字段上加入这些查询。

您想 count the distinct 记录 ID 和项目 ID。

    SELECT cust.name, 
           COUNT(DISTINCT doc.id), 
           COUNT(DISTINCT item.id)
      FROM customers AS cust
INNER JOIN documents AS doc ON doc.customer_id = cust.id
INNER JOIN documents_items AS item ON item.document_id = doc.id
  GROUP BY cust.name