2011-05-16 68 views
1

我有兩個表,我需要從(classifieds_items和附件)拉記錄。分類項目的圖像存儲在不同的表格(附件)中,每個分類的圖像可能有多個。我需要爲每個分類項目拉一張圖片。下面的聲明的問題是它會複製結果與項目有多個圖像。MySQL加入唯一

$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; 
+0

我猜你想在分組的JOIN工作,並把它在某種程度上更合適的而不是快速使用DISTINCT – haknick 2011-05-16 00:34:11

+0

如果可以有多個每個分類的附件,然後我會說查詢工作正常。如果你只想爲每個分類記錄一個記錄,那麼你可以做到這一點 - 但你想要哪個圖像? – 2011-05-16 00:44:44

回答

1

在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";` 
+0

像魅力一樣工作!謝謝 – user754948 2011-05-16 01:16:51

+0

Np。如果它有幫助,我會期待你+1。 – a1ex07 2011-05-16 13:24:30