如何使用join语句

时间:2016-09-11 02:36:44

标签: php sql phpmyadmin

如何使用JOIN语句执行此操作。我不能再想到这样做的逻辑了。我这样做是因为json data因为查询而未显示。有人可以帮我实现这个目标吗?首先,我想从enroll_ref中获取所有subj_enrolled WHERE主题等于' $ subject'。之后,我现在将使用提取的enroll_reflastname,firstname,middlename提取到std_enrolled,其中等于enroll_ref。我会用什么方法来实现这个目标?或者加入什么?

这是我的代码

if (isset($_POST['loadstudent'])) {
    $subject = $_POST['subject'];
        $section = $_POST['section'];

    $sql ="SELECT enroll_ref FROM subj_enrolled WHERE subj_descr = '$subject' AND section = '$section'";
           $result = mysqli_query($con, $sql);

           while($row = mysqli_fetch_array($result)){
            $enroll_ref = $row['enroll_ref'];


      $select = mysqli_query($con,"SELECT lastname,firstname,middlename FROM std_enrolled WHERE enroll_ref = '$enroll_ref'"); 

      if(mysqli_num_rows($select)){
            $data = array();
            while($row = mysqli_fetch_array($select)){
                  $data[] = array(
                        'firstname' => $row['firstname'],
                        'lastname' => $row['lastname'],
                         'middlename' => $row['middlename']

                        );
            }

          }
                       echo json_encode($data);
           }


}

2 个答案:

答案 0 :(得分:1)

使用inner join

内部联接返回两个表之间匹配的所有数据。

答案 1 :(得分:0)

你的sql语句中缺少一个等号:

SELECT enroll_ref FROM subj_enrolled WHERE subj_descr '$subject' AND section = '$section'";

更改为:

SELECT enroll_ref FROM subj_enrolled WHERE subj_descr = '$subject' AND section = '$section'";