0

我正在尝试从 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);
    ?>

两个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,我将不胜感激。

另外,如果有任何进一步优化此查询的方法,请告诉我。

4

1 回答 1

0

像这样试试

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 
LEFT JOIN `areamaster` as a ON a.area = c.alias
WHERE cm.company LIKE 'A%' 
GROUP BY customerkey 
ORDER BY cm.company ASC 
LIMIT 0, 50

这是编辑再试一次

于 2013-02-19T17:46:18.520 回答