繁体   English   中英

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

[英]How to select data from one table and get all associated records from another table?

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

场景是这样的:

我有两个表,分别是: 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进行区分,但仍返回每个教师的所有相关咨询信息,因为当我单击每个教师旁边的“ View Advisory按钮时,我想显示该教师在模式中持有的课程。讲师姓名,以便在讲师删除或添加新咨询的情况下更新表。

我该如何实现? 提前致谢。

您需要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 

请检查此查询:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM