我的查询如下:
$result_portlist=mysql_query("
SELECT
portfolio AS the_port,
SUM(balance * course) AS the_balance,
SUM(insurance * course) AS the_insurance
FROM banks_all
WHERE CONCAT(balance, insurance)!='0'
GROUP BY portfolio
",$db);
$myrow_portlist=mysql_fetch_array($result_portlist);
if(mysql_num_rows($result_portlist)>0) {
do {
echo '<span> value1, vaule2, value3...</span>';
$result_portlist1=mysql_query("
SELECT
department AS the_department,
SUM(balance * course) AS the_balance,
SUM(insurance * course) AS the_insurance
FROM banks_all
WHERE CONCAT(balance, insurance)!='0'
AND portfolio='$myrow_portlist[the_port]'
GROUP BY department
",$db);
$myrow_portlist1=mysql_fetch_array($result_portlist1);
if (mysql_num_rows($result_portlist1)>0) {
do {
echo '<span> value1, vaule2, value3...</span>'
$result_portlist2=mysql_query("
SELECT
manager_name AS the_manager,
SUM(balance * course) AS the_balance,
SUM(insurance * course) AS the_insurance
FROM banks_all
WHERE CONCAT(balance, insurance)!='0'
AND portfolio='$myrow_portlist[the_port]'
AND department='$myrow_portlist1[the_department]'
GROUP BY manager_name
",$db);
{
do {
echo '<span> value1, vaule2, value3...</span>';
} while ($myrow_portlist2=mysql_fetch_array($result_portlist2));
}
} while ($myrow_portlist1=mysql_fetch_array($result_portlist1));
}
} while ($myrow_portlist1=mysql_fetch_array($result_portlist1));
}
因此,对于包含40,000多行且包含portfolio
+ department
+ manager_name
的数百种组合的表,此查询需要数小时才能执行。我的想法是在开始时进行一个查询,将manager_name
分组,然后让php组portfolio
和department
。在创建了这个查询之后,我的思绪刚刚爆炸,没有剩下的空闲内存可以思考:)
请建议我如何重新排列此查询或如何简化它以减少执行时间。
提前致谢。
编辑:这是图像,我的表(嵌套表格)如何:
答案 0 :(得分:0)
之所以花费大量时间,是因为您正在执行大量查询...假设您有10个投资组合,在10个部门中,您可以进行100次查询。这个金额是疯狂的,在你的情况下减少查询的数量非常简单。
我只是在一个查询中获取所有数据,并通过汇总使用3级组:
$result=mysql_query("
SELECT
portfolio AS the_port,
department AS the_department,
manager_name AS the_manager,
SUM(balance * course) AS the_balance,
SUM(insurance * course) AS the_insurance
FROM banks_all
WHERE
CONCAT(balance, insurance)!='0'
GROUP BY
portfolio,
department,
manager_name
with ROLLUP
ORDER BY the_port,the_department,the_manager;
",$db);
echo '<table>';
while($row = mysql_fetch_assoc($result)){
if($row['the_port'] === null){
//This is the big total row... Let's skip it for now shall we?
continue;
}
echo '<tr>';
if($row['the_department'] === null){
echo '<td>Portfolio: '.$row['the_port'].'</td>';
}else{
if($row['the_manager'] === null){
echo '<td>Department: '.$row['the_port'].'</td>';
}else{
echo '<td>Manager: '.$row['the_port'].'</td>';
}
}
echo '<td>'.$row['the_balance'].'</td>';
echo '<td>'.$row['the_insurance'].'</td>';
echo '</tr>';
}
echo '</table>';
此查询将返回按产品组合分组的所有行,然后按部门分组,然后按经理分组。这将从最精细的点(第三次)返回所有行,但是使用ROLLUP
,您还将按级别为另一个组获取一行。这就像您在同一查询中完成GROUP BY portfolio,department
和GROUP BY portfolio
一样。
在汇总的行中,group by中省略的键的值将为NULL。因此,您可以轻松查看the_manager
,当它为空时表示您拥有完整的部门,当the_department
为空时您拥有完整的投资组合。