我尝试从多个表格中选择使用连接的总数时遇到问题。 COUNT
的结果不正确。MySQL COUNT与JOIN连接的多个表格
我有三个表:
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
如果您还想在没有任何文档或doc_item的情况下返回客户,请切换到LEFT JOIN,而不是INNER JOIN。 – jarlh 2015-02-23 10:34:51