代码之家  ›  专栏  ›  技术社区  ›  axsuul

需要有关几乎可以工作的联接查询的帮助

  •  1
  • axsuul  · 技术社区  · 16 年前

    我有四张桌子。

    posts
    | id      | title     |
    +---------+-----------+
    | 1       | hello     |
    | 2       | goodbye   |
    +---------+-----------+
    
    posts_tags
    | tag_id  | post_id   |
    +---------+-----------+
    | 1       | 1         |
    | 2       | 1         |
    | 2       | 2         |
    +---------+-----------+
    
    comments
    | id      | post_id    | comment   |
    +---------+------------+-----------+
    | 1       | 1          | hey       |
    | 2       | 2          | what up   |
    | 3       | 2          | blah      |
    +---------+------------+-----------+
    
    tags
    | id      | name      |
    +---------+-----------+
    | 1       | news      |
    | 2       | photos    |
    +---------+-----------+
    

    我想能够选择帖子,但结果是这样

    post.id    post.title    tags              comments
    -----------------------------------------------------
    1          hello         news,photos       1
    2          goodbye       photos            2
    

    类似的东西

    SELECT *,
           GROUP_CONCAT(tags.name) AS tags,
           COUNT(comments.id) AS comments
    FROM posts
        LEFT JOIN comments
            ON posts.id = comments.post_id
        LEFT JOIN posts_tags
            ON posts.id = posts_tags.post_id
        LEFT JOIN tags
            ON posts_tags.tag_id = tags.id
    GROUP BY posts.id
    

    我遇到的问题是没有返回正确的评论数量。相反,它似乎返回了标签的数量。请告知,谢谢您的时间:)

    1 回复  |  直到 16 年前
        1
  •  1
  •   Fozi    16 年前

    尝试计数(distinct comments.id)