Mysql

在 PHP MySQL 中,如何求和或不求和多個列?

  • September 30, 2018

我有三個表這是我的程式碼:

<table border='1'>
       <tr>
       <th>Subject</th>
       <th>Mark1</th>
       <th>Mark2</th>
       <th>Mark3</th>
       <th>Sum Marks</th>
       </tr>

<?php
   $query2 = "SELECT  students_info.s_name, subjects.subject, marks.*
           FROM  subjects
           RIGHT JOIN  (students_info
           RIGHT JOIN  marks  ON students_info.s_id = marks.s_id
               )  ON subjects.sub_id = marks.sub_id
           WHERE  students_info.s_id = '".$s_id."'";

   $result2=mysqli_query($link,$query2) OR die(mysqli_error($link));   

       while ($row=mysqli_fetch_array($result2))
       {
?>
       <tr>
           <td><?php echo $row['subject'];?></td>
           <td><?php echo $row['n1'];?></td>
           <td><?php echo $row['n2'];?></td>
           <td><?php echo $row['n3'];?></td>
           <td><?php echo $row['n1']+$row['n2']+$row['n3'];?></td>
       </tr>
<?php
       }
?>
       </table>
<?php
}
?>

輸出我的程式碼:

在此處輸入圖像描述

我希望當每個主題小於 49 的每個標記形式(標記 1、標記 2、標記 3)在單元格和標記中不起作用時,總和標記出現空值或空單元格,請查看我的程式碼並給我幫助,做這個程式碼。

可以通過將 NULL 列恢復為 0 來將它們添加到 SQL 中,例如:

SELECT students_info.s_name, subjects.subject, marks.*, 
      COALESCE(marks.n1, 0) + COALESCE(marks.n2, 0) +COALESCE(marks.n3, 0) as  sum_marks
FROM ....

引用自:https://dba.stackexchange.com/questions/216324