我无法循环使用已使用GROUP BY的表中的记录


I cant loop record from table which already use GROUP BY

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

===========================================
|No|Nama Sekolah|Alamat|Telepon|Kompetensi|
===========================================
|1 |SMP 1       |JKT   |021231 | 1.TIK1   |
|2 |SMP 2       |BDG   |021232 | 1.RPL1   |
===========================================

如果我不使用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   |
===========================================

我想要这样的结果:

===========================================
|No|Nama Sekolah|Alamat|Telepon|Kompetensi|
===========================================
|1 |SMP 1       |JKT   |021231 | 1.TIK1   |
|  |            |      |       | 2.TIK2   |
|2 |SMP 2       |BDG   |021232 | 1.RPL1   |
|  |            |      |       | 2.RPL2   |
===========================================

我使用的是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>

这是型号:

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();
}

请帮帮我。谢谢!

所以基本上您想要显示TKL1、TKL2的ol。如果是首次将group_concat用于类似j.nama_jurusan

GROUP_CONCAT(DISTINCT j.nama_jurusan SEPARATOR ',') 

在您的查询中

然后在视图中分解,中的值,然后使用foreach循环将其打印到li

只是猜测,希望能有所帮助。