【问题标题】:Retrieving post tags from tables with relationships从具有关系的表中检索帖子标签
【发布时间】:2012-02-04 22:51:30
【问题描述】:

我正在为我的作业编写一些博客软件,我有一个 posts 表、tags 表和 post_tagspost_tags 的存在是为了消除多对多关系(一个帖子可能有多个标签,一个标签可能属于多个帖子)。以下是这些表的字段:

帖子

| p_id | title | clean_title | body | published | u_id |

标签

| t_id | name | slug |

post_tags

 | t_id | p_id |

希望您能看到我在这里所做的事情,标签使用post_tags 表链接到帖子。现在,我想根据posts 表的clean_title 字段从tags 表中检索nameslug。基本上,如果我提供clean_name,我想要与该帖子关联的所有标签。我知道我必须使用 SQL JOINS,但我不知道如何使用它们。

这是我尝试过的:

$query = $this->db->query("SELECT name, slug
                           FROM tags
                           LEFT JOIN post_tags ON posts.p_id=post_tags.p_id
                           LEFT JOIN tags ON post_tags.t_id=tags.t_id
                           WHERE posts.clean_title = ?
                           ORDER BY name DESC");

但我收到此错误:Not unique table/alias: 'tags'

谢谢!

【问题讨论】:

    标签: php mysql sql database-schema


    【解决方案1】:

    您的第一个 JOIN 引用了 posts,但您不会在其他任何地方使用该表。我怀疑你的意思是:

         SELECT name, slug
         /* First table should have been `posts`? */
         FROM posts
         LEFT JOIN post_tags ON posts.p_id=post_tags.p_id
         LEFT JOIN tags ON post_tags.t_id=tags.t_id
         WHERE posts.clean_title = ?
         ORDER BY name DESC
    

    【讨论】:

    • 哇塞。知道这会很简单哈哈:P 谢谢伙计。
    【解决方案2】:

    您将加入tags 两次。更改第二个join 以加入帖子表:

    SELECT tags.name, tags.slug
    FROM tags
    LEFT JOIN post_tags ON post_tags.t_id = tags.t_id
    LEFT JOIN posts ON posts.p_id = post_tags.p_id
    WHERE posts.clean_title = ?
    

    您可以使用以下别名缩短查询:

    SELECT t.name, t.slug
    FROM tags t
    LEFT JOIN post_tags pt ON pt.t_id = t.t_id
    LEFT JOIN posts p ON p.p_id = pt.p_id
    WHERE p.clean_title = ?
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-18
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多