dongqi8863 2011-07-03 20:08
浏览 19
已采纳

如何选择我的内容以及随附的所有标签?

I've tried very hard to have a normalized database and currently have three tables like so -

  1. content (c)
  2. content_tags (ct)
  3. tags (t)

What I'm trying to do here is select some rows and return them with all the tags that are associated with it. At the moment, it only returns one tag for some reason.

Here is the code I'm using:

   SELECT *, 
          GROUP_CONCAT(t.tag) AS tags
     FROM content AS c 
LEFT JOIN category AS ca ON c.cid = ca.cid 
LEFT JOIN contenttags AS ct ON c.smid = ct.smid 
LEFT JOIN tags AS t ON ct.tid = t.tid 
LEFT JOIN users AS u ON c.uid = u.uid
    WHERE (t.tag IN ('tag1', 'tag2', 'tag3'))
 GROUP BY c.smid

It returns something like this:

  • cid
  • content
  • url
  • tag (but only one instead of multiple)
  • 写回答

3条回答 默认 最新

  • dongyangzhi0687 2011-07-04 00:24
    关注

    Do you mean to find all contents and all their tags, where at least one of their tag is in $tagArray ?

       SELECT c.*, ca.*, u.*, 
              GROUP_CONCAT(t.tag) AS tags
         FROM content AS c 
    LEFT JOIN category AS ca ON c.cid = ca.cid 
         JOIN contenttags AS ct ON c.smid = ct.smid 
         JOIN tags AS t ON ct.tid = t.tid 
    LEFT JOIN users AS u ON c.uid = u.uid
        WHERE EXISTS ( SELECT *
                       FROM contenttags ct2
                         JOIN tag t2
                           ON t2.tid = ct2.tid
                       WHERE ct2.smid = c.smid
                         AND ct2.tag IN ('$tagArray')
                     )
     GROUP BY c.smid
    

    And those LEFT JOIN can be probably turned into inner JOINs, too, without losing any results. Try it. Unless category.cid or category.uid fields can have NULL values. In that case, keep the related LEFT JOIN.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
  • ¥15 unity连接Sqlserver
  • ¥15 图中这种约束条件lingo该怎么表示出来
  • ¥15 VSCode里的Prettier如何实现等式赋值后的对齐效果?
  • ¥15 流式socket文件传输答疑
  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥100 在连接内网VPN时,如何同时保持互联网连接