简体   繁体   English

MySQL使用JOIN COUNT多个表

[英]MySQL COUNT multiple tables with JOIN

I have a problem trying to select the total from multiple tables using joins. 我尝试使用连接从多个表中选择总数时遇到问题。 The results of COUNT are not correct. COUNT的结果不正确。

I have three tables: 我有三张桌子:

Customers
id -> Primary/Autoincrement
name

Documents
id -> Primary/Autoincrement
customer_id

Documents_items
id -> Primary/Autoincrement
document_id

And I would like to obtain the total, grouped by customer name, of documents and documents items. 我想获得按客户名称分组的文件和文件项目总数。

    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

The problem is that the result of COUNT(doc.id) is equal to the result of COUNT(item.id) which is not correct. 问题是COUNT(doc.id)的结果等于COUNT(item.id)的结果,这是不正确的。

You can see a demo example of the error in SQLFiddle . 您可以在SQLFiddle中看到错误的演示示例。

Input example : 输入示例

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

Output expected : 预期产量

Name     |    Total Docs    | Total Items
John              1               2

Current output : 当前输出

Name     |    Total Docs    | Total Items
John              2               2

You want to count the distinct document id's and item id's. 您想要计算不同的文档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

Try this way: 试试这种方式:

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

Explanation: 说明:

You have to generate two result with each count. 每次计数都必须生成两个结果。 And then join those result with name field. 然后将这些结果与名称字段结合起来。

First inner query will generate the name and count of docs. 第一个内部查询将生成文档的名称和计数。 Second inner query will generate the name and count of items. 第二个内部查询将生成项目的名称和计数。 Then we will join those queries on the name field. 然后我们将在名称字段上加入这些查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM