PHP while ループ内から mysql クエリを削除し、代わりに JOIN を使用しようとしています。
質問があります
SELECT *,
SUM(CASE WHEN posmonth like '2013%' THEN ext ELSE NULL END) AS year2013,
SUM(CASE WHEN posmonth like '2012%' THEN ext ELSE NULL END) AS year2012,
SUM(CASE WHEN posmonth like '2011%' THEN ext ELSE NULL END) AS year2011,
SUM(CASE WHEN posmonth like '2010%' THEN ext ELSE NULL END) AS year2010
FROM combined c
LEFT JOIN customermaster cm ON c.alias=cm.customerkey
WHERE cm.company LIKE 'A%'
GROUP BY customerkey
ORDER BY cm.company ASC
LIMIT 0, 50
次に、これらの結果を使用して、次を使用して別のテーブル「areamaster」からデータをフェッチします。
<?php
$result = mysqli_query($link, $query);
while ($r = mysqli_fetch_object($result)) {
$alias = $r->alias;
$company = $r->company;
$a = mysqli_query($link, "SELECT area FROM areamaster WHERE areakey='$alias' LIMIT 1");
while ($t = mysqli_fetch_object($a)) { $aliasdisplay = $t->area; }
//Instead of this ^^ USE JOIN IN ORIGINAL QUERY
?>
<tr>
<td><?php print (substr($company,0,20)); ?></td>
<td><?php print (strtoupper($r->location)); ?></td>
<td><?php print $aliasdisplay; ?></td>
<td>$<?php print number_format($r->$year4V,2,".",","); ?></td>
<td>$<?php print number_format($r->$year3V,2,".",","); ?></td>
<td>$<?php print number_format($r->$year2V,2,".",","); ?></td>
<td>$<?php print number_format($r->$year1V,2,".",","); ?></td>
</tr>
<?php
}
mysqli_free_result($result);
?>
2 つの mysql テーブル構造:
areamaster:
areakey: Primary
area: What I want displayed
combined:
id:primary
posmonth: for totaling ext by Year
alias: compare to areamaster.areakey and get "areamaster.area"
location:
ext: being totaled by SUM
誰かが JOIN を書くのを手伝ってくれたら、私はそれを感謝します。
また、このクエリをさらに最適化する方法があれば教えてください。