我不能从已经使用GROUP BY的表中循环记录

Yos*_*oka 2 php mysql loops codeigniter

我想从表中循环记录字段.我在查询和GROUP BY中使用LEFT JOIN来防止结果中出现双循环.查询成功但结果如下:

===========================================
|No|Nama Sekolah|Alamat|Telepon|Kompetensi|
===========================================
|1 |SMP 1       |JKT   |021231 | 1.TIK1   |
|2 |SMP 2       |BDG   |021232 | 1.RPL1   |
===========================================
Run Code Online (Sandbox Code Playgroud)

如果我不使用GROUP BY,结果将是这样的:

===========================================
|No|Nama Sekolah|Alamat|Telepon|Kompetensi|
===========================================
|1 |SMP 1       |JKT   |021231 | 1.TIK1   |
|2 |SMP 1       |JKT   |021231 | 1.TIK2   |
|3 |SMP 2       |BDG   |021232 | 1.RPL1   |
|4 |SMP 2       |BDG   |021232 | 1.RPL2   |
===========================================
Run Code Online (Sandbox Code Playgroud)

我想要这样的结果:

===========================================
|No|Nama Sekolah|Alamat|Telepon|Kompetensi|
===========================================
|1 |SMP 1       |JKT   |021231 | 1.TIK1   |
|  |            |      |       | 2.TIK2   |
|2 |SMP 2       |BDG   |021232 | 1.RPL1   |
|  |            |      |       | 2.RPL2   |
===========================================
Run Code Online (Sandbox Code Playgroud)

我使用codeigniter框架.

这是我的观点:

<table class='table table-bordered'>
    <thead>
        <tr>
            <td>No</td>
            <td>Lokasi</td>
            <td>Alamat</td>
            <td>Telepon</td>
            <td>Kompetensi</td>
        </tr>
    </thead>
        <?php
        $i = 0;
        foreach ($row as $row) {
            $i++;
            echo"<tr>
                    <td>".$i."</td>
                    <td>".$row->nama_sekolah."</td>
                    <td>".$row->alamat."</td>
                    <td>".$row->no_telp."</td>
                    <td><ol>
                            <li>".$row->nama_jurusan."</li>
                        </ol>
                    </td>
                </tr>";
        }
        ?>
</table>
Run Code Online (Sandbox Code Playgroud)

这是模型:

function getlokasi($jenjang){
    $sql = "SELECT s.nama_sekolah, s.alamat, s.no_telp, j.nama_jurusan FROM sekolah s LEFT JOIN jurusan j ON j.id_sekolah = s.id_sekolah WHERE s.id_jenjang = '".$jenjang."' GROUP BY s.id_sekolah";
    $q   = $this->db->query($sql);
    return $q->result();
}
Run Code Online (Sandbox Code Playgroud)

请帮我.谢谢!

Ami*_*ara 5

所以基本上你想要显示olTKL1,TKL2.如果是第一次使用group_concatj.nama_jurusan

GROUP_CONCAT(DISTINCT j.nama_jurusan SEPARATOR ',') 
Run Code Online (Sandbox Code Playgroud)

在您的查询中

然后在视图中展开值,,然后使用foreach循环将其打印出来li

只是一个猜测,希望它会有所帮助.