2015-12-15 27 views
2

我想從表中循環記錄字段。我在查詢和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(); 
} 

請幫助我。謝謝!

+0

可以使用GROUP_CONCAT函數 –

+0

@Chetan Ameta確定虐待嘗試 – Yoshioka

回答

5

所以基本上你想要顯示TKL1,TKL2的ol。如果是這樣 首次使用group_concatj.nama_jurusan

GROUP_CONCAT(DISTINCT j.nama_jurusan SEPARATOR ',') 

在查詢

,然後在視圖從,爆炸的值,然後使用foreach循環將其打印在li

只是一個猜測,希望它會有所幫助。

+0

確定生病試試吧.. – Yoshioka

+0

我已經嘗試,但錯誤消息顯示「消息:未定義的屬性:stdClass的:: $ nama_jurusan」 – Yoshioka

+0

請告訴我行號和文件名,顯示錯誤 –