如何从一个表中选择数据并从另一表中获取所有相关记录?

时间:2019-02-22 13:18:06

标签: php html mysql

我正在尽最大努力简化我的问题,希望我的解释可以阐明其含义。

情况是这样的:

我有两个表,分别是:tbl_instructors,其中包含诸如教师ID和姓名之类的教师信息;以及tbl_advisory,其中包含由特定教师处理的该类的所有记录。类的CourseYearSection。所以我的桌子是这样的:

tbl_instructor:

id  | name
----+--------------
001 | Jhon Doe
002 | Kaitlyn Moore  

tbl_advisory:

instructor_id  | course        | year      |  section
---------------+---------------+-----------+-----------
001            | BSINT         | 2nd Year  | A
001            | BSINT         | 2nd Year  | C
001            | BSINT         | 2nd Year  | B
002            | BSBA          | 1st Year  | A
002            | BSBA          | 1st Year  | D

现在,我试图在我的PHP查询中使用INNER JOIN选择讲师ID和姓名及其相关的咨询信息:

<?php
$getAdvisory = "SELECT 
  ti.id AS id,
  ti.name AS name,
  ta.course AS ccourse,
  ta.year AS cyear,
  ta.section AS csection
FROM tbl_instructor as ti
INNER JOIN tbl_advisory as ta
ON ti.id = ta.instructor_id";
OpenConn()->query($getAdvisory);

if ($getAdvisory->num_rows > 0) {
    while ($row = $getAdvisory->fetch_assoc()) {
     $id = $row['id'];
     $name = $row['name'];
    }
    ?>
    <td><?php echo $id; ?></td>
    <td><?php echo $name; ?></td>
    <td><button>View Advisory</button></td>
    <?php
 }
}
?>

哪个给了我html / php表中的结果集:

id   | name          |  action
-----+---------------+-----------
001  | John Doe      | View Advisory
001  | John Doe      | View Advisory
001  | John Doe      | View Advisory
002  | Kaitlyn Moore | View Advisory
002  | Kaitlyn Moore | View Advisory

我的问题是我希望我的html表按教师ID进行区分,但仍返回每位教师的所有相关咨询信息,因为当我单击{{{1 }}按钮旁边的每个讲师姓名,以便在讲师删除或添加新咨询后我可以更新表格。

我该如何实现?预先感谢。

2 个答案:

答案 0 :(得分:0)

您需要DISTINCT子句

 SELECT DISTINCT 
  ti.id AS id,
  ti.name AS name,
  ta.course AS ccourse,
  ta.year AS cyear,
  ta.section AS csection
FROM tbl_instructor as ti
INNER JOIN tbl_advisory as ta ON ti.id = ta.instructor_id

通过这种方式,您应该获得

id   | name          |  action
-----+---------------+-----------
001  | John Doe      | View Advisory
002  | Kaitlyn Moore | View Advisory

如果值在不同的行上,则可以使用(伪)聚合函数

SELECT ti.id AS id,
ti.name AS name,
min(ta.course) AS ccourse,
min(ta.year) AS cyear,
min(ta.section)  AS csection
FROM tbl_instructor as ti
INNER JOIN tbl_advisory as ta ON ti.id = ta.instructor_id
GROUP BY id, name 

答案 1 :(得分:-1)

请检查此查询:

SELECT    ti.*, GROUP_CONCAT( CONCAT( ta.course, ' ' , ta.year,' ', ta.section ) separator ' - ') as ColumnName 
FROM tbl_instructor as ti
INNER JOIN tbl_advisory as ta ON ti.id = ta.instructor_id 
GROUP BY ti.idid  

输出:

      | name          |  action
 -----+---------------+-----------
 001  | John Doe      | BSINT 2nd Year a - BSINT 2nd Year b - BSINT 2nd Year c
 002  | Kaitlyn Moore | BSBA 1st Year d - BSBA 1st Year a