2010-07-22 128 views
1

這是我第一次使用JOIN子句,並且遇到了問題。我想回顯我的項目的所有必要信息,但我不明白如何回顯一個項目的所有標籤,現在,如果爲一個項目分配了多個標籤,我會得到一個包含項目重複但列表不同的標籤的列表項目。有任何想法嗎?更好的方法來做到這一點,也非常感謝。SQL JOIN獲取項目的名稱和所有標籤

$query = "SELECT categories.id, categories.category, spots.spot_name, spots.category_id, spots.description, spots.slug, districts.id, districts.district, tags.spot_id, tags.tag ". 
"FROM categories, spots, districts, tags ". 
    "WHERE categories.id = spots.category_id AND districts.id = spots.district_id AND tags.spot_id = spots.id"; 

$result = mysql_query($query); 
if (!$result) { 
    die('Invalid query: ' . mysql_error()); 
} 

while ($row = @mysql_fetch_array($result)){ 
echo '<tr><td style="background:#000; color:#ccc;" class="tooltip" title="'.$row["description"].'Tags: '.$row["tag"].'"><a style="color:#fff;" href="/'.$row["slug"].'">'.$row["spot_name"].'</a></td> 
<td>'.$row["category"].'</td> 
<td>'.$row["district"].'</td> 
<td>****</td> 
</tr> 
'; 
} 

萬分感謝,

安德斯

回答

0

更改您的查詢,並添加LEFT JOIN這樣的: $查詢=「選擇c.id,c.category,s.spot_name,S .category_id,s.description「。 「s.slug,d.id,d.district,t.spot_id,t.tag」。 「從類別AS c,點AS s,區AS d」。 「JOIN標記AS t ON s.id = t.spot_id」。 「WHERE c.id = s.category_id AND d.id = s.district_id」;

+0

嗨,感謝您的快速回復,但這給了我完全相同的結果我的代碼。任何關於如何讓所有標籤都回應一個項目並且沒有重複項目(點)在我的表中迴應的建議? – 2010-07-22 07:14:24

+0

哦!抱歉!你是對的。有一個簡單的解決方案。你可以在PHP中合併同一個ID的記錄:D – 2010-08-01 08:10:17

0

這是您的查詢的外觀更好看:

SELECT c.id, c.category, s.spot_name, s.category_id, s.description, s.slug, d.id, d.district, t.spot_id, t.tag 
    FROM spots AS s 
    LEFT JOIN categories AS c ON c.id = s.category_id 
    LEFT JOIN districts AS d ON d.id = s.district_id 
    LEFT JOIN tags AS t ON t.spot_id = s.id 

爲了讓你想發出此查詢的所有景點:

SELECT c.id, c.category, s.spot_name, s.category_id, s.description, s.slug, d.id, d.district 
    FROM spots AS s 
    LEFT JOIN categories AS c ON c.id = s.category_id 
    LEFT JOIN districts AS d ON d.id = s.district_id 

現在你也可以遍歷所有的斑點和得到他們的標籤:

'SELECT t.tag FROM tags WHERE t.spot_id = '. (int)$spot_id 
+0

謝謝,但你在最後一步中的循環意味着什麼?你的意思是每次都有一個正常的PHP while循環和一個新的SQL查詢嗎?這會讓所有的事情都變慢嗎? – 2010-07-25 07:06:11

+0

是的,那就是我的意思。 2個查詢速度較慢,但​​我認爲這是唯一的方法,如果你想防止重複的項目。因爲當你將一個表全部加入並且一個項目具有多個標籤時,它將會出現多少個項目。 – JochenJung 2010-07-25 09:40:18