【问题标题】:Complicated Sub-query - is this possible?复杂的子查询 - 这可能吗?
【发布时间】:2010-09-18 18:00:25
【问题描述】:

我有 2 个表:一个存储标签,另一个存储文章。有一种“按标签获取文章”模式,它基本上获取所有标签为“x”的文章。在我的文章表中,我使用了一个名为 Tags 的文件,它以“tag1、tag2、tag3、...”的模式存储数据。

所以我想通过一个这样的查询来完成所有工作:

SELECT *, 
       (SELECT tagname 
          FROM `tags_table` 
         WHERE tagurn LIKE 'x') as TAGNAME 
  FROM `articles_table` 
 WHERE (Tags LIKE 'TAGNAME,%' OR Tags LIKE '%, TAGNAME' ... and so on)

我什至不知道这是否可能,但我真的很想使用单个查询(带有子查询)而不是两个不同的查询。

【问题讨论】:

    标签: mysql select many-to-many subquery sql-like


    【解决方案1】:

    这是在数据库中存储多对多关系的错误方法。

    你应该有这样的架构:

         articles: [PK] article_id, ... (should have no reference to tags)
             tags: [PK] tag_id, tag_name, ...
    articles_tags: [FK] article_id, [FK] tag_id
    

    [PK] = 主键,[FK] = 外键

    其中articles_tagsjunction table。现在,您可以获得带有给定标签的所有文章(如果您知道tag_id,您甚至不需要JOIN):

        SELECT article_id, ...
          FROM articles_tags
    INNER JOIN tags ON tags.tag_id = articles_tags.tag_id
         WHERE tag_name = 'TAGNAME'
    

    【讨论】:

      猜你喜欢
      • 2012-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-07
      • 1970-01-01
      相关资源
      最近更新 更多