如何合并数据库表

时间:2018-07-18 01:15:36

标签: php mysql join

请,我有一个需要帮助的问题。我经历了其他用户提出的类似问题,但似乎没有一个能解决我的问题。

我有3张桌子(考试,测试,课堂作业),具有类似的列,用于存储不同主题的分数,即英语,数学和押韵。它使用分配的ID识别学生。我希望能够将每个学科的分数相加以获得一个值,以便我可以使用循环与其他学生进行比较。即在数学中,一名学生在课堂作业20中在考试45中,在考试20中获得了分数。总计为85。我如何在类似于以下查询的类似查询中合并此表,以便于操作:

require_once("con.php");

$class="Preschool1";

$id="12345";

$project = mysqli_query(
             $mysqli,
             "SELECT * FROM `exam` WHERE `class`='".$class."' && `ID`='".$id."'  ")
           or die("Database not found");
if(mysqli_num_rows($project)==true)
{
    $parray=mysqli_fetch_array($project);
}

else
{
   // ...
}

1 个答案:

答案 0 :(得分:0)

这对我有用。还能够从所有表中获取特定个人的记录,并可以按我的喜好进行操作..谢谢

<?php
include 'con.php';
$name="Stanley Macron";
$sql = '
SELECT 
project_nursery.fname as fname,
project_nursery.sn as sn,
project_nursery.Literacy as literacy,
project_nursery.Numeracy as numeracy,
nursery_result_exam.sn as sn2,
nursery_result_exam.fname as fname2,
nursery_result_exam.Literacy as literacy2,
        nursery_result_exam.Numeracy as numeracy2
    FROM Project_nursery
    LEFT JOIN nursery_result_exam ON (project_nursery.fname = nursery_result_exam.fname)';

if($result = mysqli_query($mysqli, $sql)) {
    if(mysqli_num_rows($result) > 0) {
        while($row = mysqli_fetch_array($result))
        {
                     $fname=$row['fname'];


        if($name==$fname)
        {

        echo "  <table class=\"table table-bordered\">";
        echo "<tr>";
        echo "<th>sn</th>";
        echo "<th>Name</th>";
        echo "<th>P Literacy</th>";
        echo "<th>E Literact</th>";
        echo "<th>sn</th>";
        echo "<th>P Numeracy</th>";
        echo "<th>E Numeracy</th>";

        echo "</tr>";

            echo "<tr>";
            echo "<td>" . $row['sn'] . "</td>";
            echo "<td>" . $row['fname']. "</td>";
            echo "<td>" . $row['literacy'] . "</td>";
            echo "<td>" . $row['numeracy'] . "</td>";
            echo "<td>" . $row['sn2'] . "</td>";
            echo "<td>" . $row['literacy2'] . "</td>";
echo "<td>" . $row['numeracy2'] . "</td>";
 echo "</tr>";
        }}
        echo "</table>";
    }
    else{echo "not found";}

    } else {
        echo "No records matching your query were found.";
    }
   mysqli_close($mysqli);
?>