我是mysql的新手。

我想为我的博客开发一个简单的标记系统,并遇到了制作3张桌子的“ Toxi”解决方案。

因此,我有3张桌子:

`blog` containing `id` and `title`.
`blog_tags` containing `id` and `tags_id` and `blog_id`.
`tags` containing `id` and `name`.


tags_idInternal Relation表中连接到idtags
同样,blog_idInternal Relation表中连接到idblog

因此,当在我的函数中(获得与单个博客有关的所有标签的数组)时,例如执行查询(将Blog id作为函数中的参数传递),

    $result = mysql_query("SELECT tags_id FROM blog_tags WHERE blog_id = '".$id."'");
    $tags = array();
    if($result === FALSE) {
        die(mysql_error()); // TODO: better error handling
    }
    while($row = mysql_fetch_assoc($result)) {
        $tags[] = I don't know what should come over here?
    }
    return $tags;


或者在此Toxi实现中还有其他方法可以执行查询吗?

最佳答案

更新您需要一个简单的JOIN。您的查询应如下所示

SELECT bt.tags_id, t.name
  FROM blog_tags bt JOIN tags t
    ON bt.tags_id = t.id
 WHERE bt.blog_id = n -- < n is an id of a blog


这是SQLFiddle演示。

现在php非常简单

$sql = "SELECT bt.tags_id, t.name
          FROM blog_tags bt JOIN tags t
            ON bt.tags_id = t.id
         WHERE bt.blog_id = $id";
$result = mysql_query($sql);
if($result === FALSE) {
    die(mysql_error()); // TODO: better error handling
}
$tags = array();
while($row = mysql_fetch_assoc($result)) {
    $tags[] = $row['name'];
}
...


附带说明:切换到PDO或mysqli。不推荐使用mysql_ *扩展名。在PDO中,可以使用语法糖fetchAll()。而且更重要的是学习使用准备好的语句。现在,您的代码容易受到sql注入的攻击。

08-04 11:47