使用MySQL和php通过三个表联合计算平均值的简单方法

时间:2017-05-23 18:44:43

标签: php mysql union

我有三个数据库表

        Graduate_survey
      g_id(pk)AI  PO  PO1  PO2 Program_name year1 year2

        Alumni_survey
      a_id(pk)AI  PO  PO1  PO2 Program_name year1 year2

        faculty_survey
      f_id(pk)AI  PO  PO1  PO2 Program_name year1 year2

将值插入这些表后,我需要计算平均值并将平均值存储在另一个表total_survey中

   total_survey
   t_id(pk)AI  PO  PO1  PO2 Program_name year1 year2

使用$_session插入Program_name,year1,year2。  如何使用MySQL查询计算平均值并使用php将新值存储在另一个表中?我的代码如下所示,但不起作用。

             <?php
             @include("connection.php");
             error_reporting(0);
             $program=$_POST['Program_name'];
             $year1=$_POST["year1"];
             $year2=$_POST["year2"];
             $po=$_POST["total_PO"];
             $po1=$_POST["total_PO1"];
             $po2=$_POST["total_PO2"];
             $_SESSION['SProgram_name']=$program;
             $_SESSION['Syear1']=$year1;
             $_SESSION['Syear2']=$year2;
             if($_POST['submit'])
            {
              $sql= "SELECT AVG(t.PO) AS total_PO, AVG(t.PO1) AS 
              total_PO1, AVG(t.PO2) AS total_PO2
              FROM ( SELECT PO,PO1,PO2
              FROM Graduate_survey
              UNION ALL
              SELECT PO,PO1,PO2
              FROM alumni_survey
              UNION ALL
              SELECT PO,PO1,PO2
              FROM faculty_survey
              )*t";
             $rData=mysql_query($sql);
             $res=mysql_fetch_array($rData);

              $sql="select * from total_survey";
             $rData=mysql_query($sql);
             $res=mysql_fetch_array($rData);
             $sql="insert into total_survey 
            values('','$po','$po1','$po2','$program','$year1','$year2')";
             mysql_query($sql);

             }
            ?>
           <form method="post">
           <p align="center"><input type="submit" name="submit" value="Click 
           here to calculate the final indirect assesment">
           </form>

假设在graduate_survey表中,PO列包含70,PO1包含60,PO2包含80.在alumni_survey中,PO列包含60,PO1包含70,PO2包含90.在faculty_survey中,PO列包含90,PO1包含80和PO2包含60.我需要的是平均(PO + PO + PO),平均值(PO1 + PO1 + PO1),平均值(PO2 + PO2 + PO2)按所有三个表格组合并ID

1 个答案:

答案 0 :(得分:1)

您需要在UNION上进行平均并将其包装到INSERT查询中,例如:

INSERT INTO total_survey (PO, PO1, PO2)
SELECT AVG(PO), AVG(PO1), AVG(PO2) 
FROM (
 SELECT PO, PO1, PO2 FROM graduate_survey

 UNION

 SELECT PO, PO1, PO2 FROM Alumni_survey

 UNION

 SELECT PO, PO1, PO2 FROM faculty_survey
) a;