开发者

MySQL JOIN UnIQUE

I have two tables that I need to pull records from (classifieds_items and attachm开发者_StackOverflowents). The images for the classified items are stored in a different table (attachments) and there can be multiple images for each classified. I need to pull just one image for each classified item. The problem with the statement below is it will duplicate the results with the items thas have multiple images.

$sql = "SELECT * 
          FROM classifieds_items
          JOIN (attachments) ON (attachments.attach_rel_id = classifieds_items.item_id)
         WHERE active = 1 
           AND open = 1 
           AND date_expiry > ". time()." 
           AND attachments.attach_rel_module = 'classifieds' 
      ORDER BY RAND() 
         LIMIT 4";   

$rs = mysql_query($sql);    

if(mysql_num_rows($rs)>0) {
  while($row=mysql_fetch_array($rs)) {
  $dtl_list .="<div class='fclass'>
                 <span class='fctitle'><a class='albumlnk' href='#'>".stripslashes($row['name']). '</a></span><br />
                 <img src="uploads/'.stripslashes($row['attach_thumb_location']).'" /><br />
                 '.stripslashes($row['price'])."
               </div>";
  }
}

echo $dtl_list;


In mysql you can just add GROUP BY classifieds_items.item_id :

`$sql = "SELECT *   
          FROM classifieds_items  
          JOIN (attachments) ON (attachments.attach_rel_id = classifieds_items.item_id)  
         WHERE active = 1   
           AND open = 1   
           AND date_expiry > ". time()."   
           AND attachments.attach_rel_module = 'classifieds'   
       GROUP BY classifieds_items.item_id  
      ORDER BY RAND() 
         LIMIT 4";`
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜