【问题标题】:Displaying Multiple values from a Junction table with Explode in PHP MySQL在 PHP MySQL 中使用 Explode 显示联结表中的多个值
【发布时间】:2017-05-02 13:36:35
【问题描述】:

我正在做学校项目。我为 TeacherSubjects 制作了一个连接表。 Teacher 表包含 t_id 和 t_name,Subjects 表包含 sub_id 和 sub_name。而在联结名称中,我制作了 t_id 和 sub_id 的外键。现在当我选择多个主题然后在 UI 中显示它时。如果我选择 3 个主题,它会重复 t_id 3 次。我只想显示 t_id 一次,其中 3 个 sub_id 用逗号将它们分隔在一个表中。 Click here to see the screenshot of the current table

这是我写的当前代码:

<?php

    $que = "select teacher.t_name,teacher.qualification,teacher.gender,subject.sub_name from teacher join teach_sub_junction on teacher.t_id=teach_sub_junction.teacher_id join subject on subject.sub_id=teach_sub_junction.subject_id";
    $i = 1;

        if($row = mysql_query($que)){

            while($result = mysql_fetch_assoc($row)){
                 $tname = $result['t_name'];
                 $qualification = $result['qualification'];
                 $gender = $result['gender'];
                 $sub_name = $result['sub_name'];
                 ?>

            <tr>
                <td><?php echo $i; $i++; ?></td>
                <td><?php echo $tname; ?></td>
                <td><?php echo $gender; ?></td>
                <td><?php echo $qualification; ?></td>
                <td><?php echo $sub_name; ?></td>
            </tr>
<?php       }
        }
?>  

【问题讨论】:

    标签: php mysql database


    【解决方案1】:

    您可以使用 GROUP_CONCAT(subject.sub_id) 和 GROUP BY teacher.t_id 显示 t_id 一次,其中 3 个 sub_id 用逗号将它们分隔在一个表格中。

    参考:GROUP BY clause to get comma-separated values in sqlite

    【讨论】:

      猜你喜欢
      • 2013-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-22
      • 1970-01-01
      相关资源
      最近更新 更多