2011-03-05 55 views
0

我有一個文件,那麼對於每個文件都有關於該文件的多個註釋。我能夠成功地加入這兩個表格,評論和文件,但是當我嘗試查看顯示文件及其評論的頁面時,頁面顯示文件名稱n次(n對應於評論記錄的數量該特定文件)。SQL加入CodeIgniter

我將如何顯示文件名稱以及顯示註釋?

<table width="40%" align="center"> 
     <?php foreach($rows as $file):?> 
     <tr> 
      <td width="70%" id="title"><?php echo $file->name; ?></td> 

     </tr> 
     <?php endforeach;?> 
    </table> 

    <table width="40%" align="center" frame="above" style="margin-top:10px; border-top-width:3px; border-top-color:#666666"> 
     <?php foreach($rows as $file):?> 
     <tr> 
      <td width="15%"></td> 
      <td width="45%" id="name">FILESIZE:</td> 
      <td width="40%" id="txt3"><?php echo $file->size; ?></td> 
     </tr> 
     <tr> 
      <td></td> 
      <td id="name">DATE UPLOADED:</td> 
      <td id="txt3"><?php echo $file->dateUploaded;?></td> 
     </tr> 
     <?php endforeach;?> 
    </table> 
    <!--COMMENTS --> 

    <table align="center" frame="above" style="margin-top:10px; border-top-width:3px; border-top-color:#666666" width="40%"> 
     <tr> 
      <td><h3>Comments</h3></td> 
     </tr> 
     <tr><?php foreach($rows as $comment):?> 
      <td><?php echo $comment->comm;?></td> 
     </tr><?php endforeach;?> 


    </table> 
+0

粘貼查詢/相關的代碼 – yoda 2011-03-05 06:26:44

回答

0

您可以使用

GROUP_CONCAT() 
在你加入

SELECT person.id AS id, name, GROUP_CONCAT(role.role SEPARATOR ',') AS roles 
    FROM person 
    LEFT OUTER JOIN person_role ON person.id=person_role.person_id 
    LEFT OUTER JOIN role ON person_role.role_id=role.id 
    GROUP BY id 
    ORDER BY id; 

是一個教程在 http://dev-loki.blogspot.com/2008/01/aggregate-join-results-with-mysql-using.html

一個例子,沒有看到你的方案不能給好得​​多。

編輯:無論如何嘗試。

SELECT files.*, GROUP_CONCAT(comments.comment SEPARATOR ',') as comments_list 
FROM files 
LEFT JOIN comments on files.id = comments.id 
GROUP BY id 
ORDER BY id 
+0

刪除PLS,可以」 t後代碼格式正確,因此必須添加我自己的答案。 codeigniter中的 – 2011-03-05 06:32:46

+0

,我從不使用活動記錄;) – Orbit 2011-03-05 06:33:12

0

添加到軌道上,在笨如果您使用ActiveRecord這將是: (對不起,我不能在評論格式代碼)

$這個 - > DB->選擇( 'person.id AS id,name,GROUP_CONCAT(role.role SEPARATOR',')AS roles',false);

$ this-> db-> from('person');

$ this-> db-> join('person_role','person.id = person_role.person_id','left outer');

$ this-> db-> join('role','person_role.role_id = role.id','left outer');

$ this-> db-> group_by('id');

$這個 - > DB-> ORDER_BY( 'ID'):

$這個 - > DB-> get()方法;

0

以及它看起來像你呼應的則返回

你行越來越像

名返回的每一行的文件名|大小|評論1
名稱|大小|註釋2

所以乾脆不要做foreach ($rows as $file)將每次打印出的文件名,只是改變

<?php foreach($rows as $file):?> 
     <tr> 
      <td width="70%" id="title"><?php echo $file->name; ?></td> 

     </tr> 
     <?php endforeach;?> 

<tr> 
      <td width="70%" id="title"><?php echo $rows[0]->name; ?></td> 

     </tr>