这是我的第一个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>
';
}
万分感谢,
的Anders
答案 0 :(得分:0)
更改您的查询并添加左连接,如下所示: $ query =“SELECT 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”;
答案 1 :(得分: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