简体   繁体   English

MySQL联接不唯一

[英]MySQL JOIN UnIQUE

I have two tables that I need to pull records from (classifieds_items and attachments). 我有两个表需要从中提取记录(classifieds_items和附件)。 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 : 在mysql中,您可以仅添加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";`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM