MySQL何时获取使用COUNT CASE WHEN函数创建的多个字段的总和?在同一个查询中还是在 PHP 之后?

问题描述 投票:0回答:1

我有一个 mysql 查询,它使用

COUNT(CASE WHEN)
函数选择数据并返回多个字段的总计。我现在想要完成的是获取所有这些字段中的一些字段,以便查看总数是
> 0
还是
= 0
。我只是不确定是否可以在同一个 MySQL 查询中执行此操作,或者在循环返回的数据时是否应该通过 PHP 获取总和。

下面是我的查询,之后是我认为可能有效的想法,但如果有人可以向我展示一种更好/更有效/更干净的方法来获得相同的结果,我将非常感激。

foreach ($iconArray as $icon) {
    
     $query = "
        SELECT teacher_type, link_url, link_title,
          COUNT(CASE WHEN icon_type = '{$icon}' AND row_value = 1 AND link_column = 1 THEN 1 END) AS location1,
          COUNT(CASE WHEN icon_type = '{$icon}' AND row_value = 1 AND link_column = 2 THEN 1 END) AS location2,
          COUNT(CASE WHEN icon_type = '{$icon}' AND row_value = 1 AND link_column = 3 THEN 1 END) AS location3,
          COUNT(CASE WHEN icon_type = '{$icon}' AND row_value = 1 AND link_column = 4 THEN 1 END) AS location4,
          COUNT(CASE WHEN icon_type = '{$icon}' AND row_value = 2 AND link_column = 1 THEN 1 END) AS location5,
          COUNT(CASE WHEN icon_type = '{$icon}' AND row_value = 2 AND link_column = 2 THEN 1 END) AS location6,
          COUNT(CASE WHEN icon_type = '{$icon}' AND row_value = 2 AND link_column = 3 THEN 1 END) AS location7
          FROM ww_click_tracking 
        WHERE click_date BETWEEN {$date_clause}
        AND teacher_type = {$value}";

        $result = mysqli_query($link, $query);

//HERE IS WHERE I WANT TO CHECK IF ALL OF THE LOCATIONS LOCATION 1-7 ADDED TOGETHER ARE GREATER THAN 0. IF NOT THERE IS NO REASON TO CONTINUE ON. 
  for ($i=1,$i <=7, $i++) {
      $locationTotal +=  $result['location'. $i];
  }
   if ($locationTotal > 0){
     //SOMETHING TO ACTUALLY REPORT SO CONTINUE DOING YOUR THANG!
      while($row = mysqli_fetch_array($result)){
    
      }
   //ELSE 0 THEN CURRENT ICON HAD NO CLICKS TO REPORT.
   }
} //END OF FOREACH ICON LOOP
php mysql arrays sum
1个回答
0
投票

您可以通过添加以下条件求和在 MySQL 端处理此问题:

SELECT ...,
    SUM(icon_type = '{$icon}' AND (
        (row_value = 1 AND link_column BETWEEN 1 AND 4) OR
        (row_value = 2 AND link_column BETWEEN 1 AND 3)
    ) AS locationTotal
© www.soinside.com 2019 - 2024. All rights reserved.