【问题标题】:SQL JOIN get name and all tags for itemSQL JOIN 获取项目的名称和所有标签
【发布时间】:2010-07-22 06:49:57
【问题描述】:

这是我的第一个 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>  
';
}

谢谢一百万,

安德斯

【问题讨论】:

    标签: php mysql join


    【解决方案1】:

    更改您的查询并添加左连接,如下所示: $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”。 “加入标签 AS t ON s.id = t.spot_id”。 "哪里 c.id = s.category_id 和 d.id = s.district_id";

    【讨论】:

    • 嗨,感谢您的快速回复,但这给了我与我的代码完全相同的结果。关于如何让一个项目的所有标签回显而不在我的表中回显重复项目(点)的任何建议?
    • 哦!对不起!你是对的。有一个简单的解决方案。您可以在 PHP 中合并相同 id 的记录:D
    【解决方案2】:

    这就是您的查询看起来更好阅读的方式:

    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
    

    【讨论】:

    • 谢谢,但最后一步的循环是什么意思?你的意思是一个普通的 PHP while 循环,每次都有一个新的 SQL 查询吗?这不会减慢一切吗?
    • 是的,这就是我的意思。 2个查询速度较慢,但​​我认为这是防止重复项目的唯一方法。因为当你在一个表中加入所有并且一个项目有多个标签时,它会出现与项目一样多的次数。
    猜你喜欢
    • 1970-01-01
    • 2021-08-14
    • 1970-01-01
    • 2021-07-10
    • 2020-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多