获取Totals打开文档(MySQL QUERY)

时间:2015-07-02 18:21:02

标签: php mysql

h ello all,

我试图从while:

获取$ total_open_docs
TABLE finance_folders
folder_id
folder_title
folder_status

TABLE finance_documents
document_id
document_folder_id
document_type
document_closed (0 or 1 value)


SELECT *,
document_folder_id AS total_open_docs, COUNT(*)
FROM finance_documents 
LEFT JOIN finance_folders ON folder_id = document_folder_id
WHERE document_closed = 0
GROUP BY document_folder_id


$i=0;
while ($i < $num) {
$folder_id = mysql_result($result,$i,"folder_id");
$total_open_docs = mysql_result($result,$i,"total_open_docs");
}

... table results ...

$i++;
}

我有10多条记录,但$ total_open_docs只返回2

我想得到这样的结果:

Folder    Open Documents
0001      10
0002      8
0003      1
0004      16

任何帮助?

1 个答案:

答案 0 :(得分:1)

查询应为:

SELECT document_folder_id, IFNULL(COUNT(*), 0) AS total_open_docs
FROM finance_documents 
LEFT JOIN finance_folders ON folder_id = document_folder_id
WHERE document_closed = 0
GROUP BY document_folder_id

别名total_open_docs应分配给计数,而不是文件夹ID。

PHP代码应为:

echo "<table><tr><th>Folder</th><th>Open Documents</th></tr>";
while ($row = mysql_fetch_assoc($result)) {
    echo "<tr><td>{$row['document_folder_id']}</td><td>{$row['total_open_docs']}</td></tr>";
}
echo "</table>";

当变量$i - mysql_fetch_assoc()到达结果的末尾时,无需返回false。这个循环是处理SQL查询结果的标准习惯用法。

顺便说一句,mysql扩展程序已过时,您应该转换为PDOmysqli。但是这个循环的基本结构与两者都是一样的。