【发布时间】:2018-06-14 22:28:18
【问题描述】:
我需要优化查询。 脚本返回一个简单的表格结果,如下所示。
我想加快结果速度,也许一种解决方案是将 montly 查询合并到一个中。
什么是快速获得listing的最佳和正确方法?
表格
YAER 2018
ID NAME JAN FEV MAR APR MAY JUN JUL AUG SEP OCT NOV DEC
00001 PAUL OK OK OK OK - OK - - - - - -
00002 MARK OK OK OK - - - OK - - - - - -
00003 JACK OK - - - - - OK - - - - - -
more 50K lines
我的数据库很简单
USERS
user_id
user_name
DOCUMENTS
document_id
document_user_id
document_date
document_file
首先,我得到一个用户,这样
$query_users = " SELECT user_id, user_name FROM users ";
$res_users = mysqli_query($mysqli,$query_users) or die(mysqli_error($mysqli));
并用一段时间创建一个表
<table style="width:100%">
<tr>
<th>ID</th>
<th>NAME</th>
<th>JAN</th>
<th>FEB</th>
<th>MAR</th>
<th>APR</th>
<th>MAY</th>
<th>JUN</th>
<th>JUL</th>
<th>AUO</th>
<th>SEP</th>
<th>OCT</th>
<th>NOV</th>
<th>DEC</th>
</tr>
<?php
while($row = mysqli_fetch_assoc($res_users)) {
$user_id = $row['user_id'];
$user_name = $row['user_name'];
?>
<tr>
<td><?php echo $user_name; ?></td>
// For each month I run this query to check if user have document on year
<?
// --------------------------------------------------------------------------------------------
// GET JAN DOCS
// --------------------------------------------------------------------------------------------
$query_doc_month_01 = "
SELECT document_id, document_date,
SUM(documento_date) AS total_documents
FROM documents
WHERE document_user_id = '$user_id'
AND document_date = '$year-01-00'
LIMIT 1
";
$res_doc_month_01 = mysqli_query($mysqli,$query_doc_month_01) or die(mysqli_error($mysqli));
while($row_month_01 = mysqli_fetch_assoc($res_doc_month_01)) {
$document_month_01_id = $row_month_01['document_id'];
?>
<td <? if ($document_month_01 == '') { echo 'bgcolor="#f1f1c1"'; } ?>>
<? if ($document_month_id == '') { echo '- - -'; } else { echo $document_month_01_id; } ?>
</td>
<?php
}
?>
<?
// --------------------------------------------------------------------------------------------
// SAME ABOVE TO GET FEB DOCS
// SAME ABOVE TO GET MAR DOCS
// ETC ETC
// --------------------------------------------------------------------------------------------
?>
</tr>
<?php
}
mysqli_close($mysqli);
?>
</table>
【问题讨论】:
-
$year在哪里初始化? -
上一页 $year= '2018';我编辑并添加
标签: php mysql query-optimization