【问题标题】:SQL Joining 3 tables tag system codeigniterSQL Joining 3表标签系统codeigniter
【发布时间】:2012-06-11 20:21:17
【问题描述】:

我一直在尝试为我的帖子设计一个标签系统,但我无法获得我想要的值。相反,我似乎无法理解表连接的逻辑。我试图找到信息来帮助我,但我想我需要有人真正奠定基础。

无论如何,这些是我的表格(缩短帖子表格);

POSTS
post_id
post_title
post_freetext

POST_TAGS
post_id
tag_id

TAGS
tag_id
tag_text

我想要做的是获取连接到单个标签的所有帖子。

我的 CodeIgniter 代码如下所示;

   $this->db->select('*');
   $this->db->from('posts');
   $this->db->join('post_tags', 'post_tags.post_id = posts.post_id' ,'inner');
   $this->db->join('tags', 'tags.tag_id = posts.post_id', 'inner');
   $this->db->where('tag_text =', $tagid);
   $this->db->order_by('posts.post_id', 'desc');
   $q = $this->db->get();

在这种情况下,$tagid 是我正在寻找的字符串(读取标签)。

我成功地连接了两个表并获取了帖子,但后来我意识到我无法让用户查看所有标签(因此我需要一个单独的“标签”表)。但似乎无法做到这一点。

任何帮助都将不胜感激,我确实意识到这个问题可能已被多次回答 - 仍然无法理解逻辑。

【问题讨论】:

    标签: sql codeigniter join tags


    【解决方案1】:

    关于加入此页面的逻辑可能会有所帮助

    http://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins

    在您的代码中,您在第二次加入时出错

    $this->db->join('tags', 'tags.tag_id = posts.post_id', 'inner');

    这两个表没有连接(外键在哪里,它指向哪里)。

    您必须使用表 post_tags 而不是帖子 所以使用这样的东西: 'post_tags.tag_id = tags.tag_id'

    【讨论】:

    • 这是一个完美的逻辑图,一直在找这样的东西,非常感谢!
    【解决方案2】:
    $this->db->select('*');
       $this->db->from('posts');
       $this->db->join('post_tags', 'post_tags.post_id = posts.post_id' ,'inner');
       $this->db->join('tags', 'tags.tag_id = post_tags.tag_id', 'inner');
       $this->db->where('tag_text', $tagid);
       $this->db->order_by('posts.post_id', 'desc');
       $q = $this->db->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-07
      • 2020-10-18
      • 1970-01-01
      相关资源
      最近更新 更多