我使用此查询来获取文件夹包含的文档数量:
$query = "
SELECT
*,
count(*) as number_documents
FROM
table_documents
LEFT JOIN
table_folders ON folder_id = document_folder_id
GROUP BY
document_folder_id
ORDER BY
number_documents DESC
";
我无法获取包含0个文档的文件夹,如何获取文件夹:
FOLDER 1 - 100份文件
FOLDER 2 - 35个文件
文件夹3 - 0文件
TABLES:
**table_folders**
folder_id
folder_description
folder_active
**table_documents**
document_id
document_folder_id
document_description
document_file
答案 0 :(得分:0)
我认为您必须从文档文件夹中汇总文档。尝试查询
SELECT d.document_folder_id
, SUM(d.documents) as number_documents
FROM table_documents d
LEFT
JOIN table_folder f
ON f.folder_id = d.document_folder_id
GROUP BY d.document_folder_id
因为你明确解释了表结构。我已经在本地创建了表并尝试过,尝试我在本地尝试过的查询
create table table_documents(id int,doc int);
insert into table_documents values
(1,100),
(2,35),
(3,0),
(1,101),
(2,36),
(3,0);
create table table_folder(id int);
insert into table_folder values
(1),(2),(3);
SELECT d.id
, SUM(d.doc) as number_documents
FROM table_documents d
LEFT
JOIN table_folder f
ON f.id = d.id
GROUP
BY d.id;// query for your output
答案 1 :(得分:0)
这将有效:
SELECT
*,
sum(if (document_folder_id is null,0,1)) as number_documents
FROM
table_folders
LEFT JOIN
table_documents ON document_folder_id = folder_id
GROUP BY
folder_id
ORDER BY
number_documents DESC