使用PHP MySQL中的爆炸显示Junction表中的多个值

时间:2017-04-30 08:33:23

标签: php mysql database

我正在从事学校项目。我为教师主题制作了联结表。 教师表包含t_id和t_name,主题表包含sub_id和sub_name。在联结名称中,我创建了t_id和sub_id的外键。现在,当我选择多个主题,然后在UI中显示它。如果我选择3个主题,它会重复t_id 3次。我只想用3个sub_id显示t_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       }
        }
?>  

1 个答案:

答案 0 :(得分:0)

您可以使用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