1

这是我的数据库架构:

Post:
id
title
body
date

Tag:
id
title

Post_Tag:
id
id_post
id_tag

Comment:
id
id_post
body
date

这是显示带有所有关联标签和评论编号的帖子的查询。

SELECT
    p.ID,
    p.title,
    p.body,
    p.c_date,
    GROUP_CONCAT(DISTINCT CONCAT_WS('|', CAST(t.ID AS CHAR), t.title) SEPARATOR ';') AS tags,
    COUNT(c.ID) AS comments
FROM Post p
    LEFT JOIN Comment c ON p.ID = c.id_post
    LEFT JOIN Post_Tag pt ON p.ID = pt.id_post
    LEFT JOIN Tag t ON pt.id_tag = t.ID
GROUP BY p.ID, p.title, p.body, p.c_date
ORDER BY p.c_date DESC

问题是评论的编号是错误的

如果帖子有 3 个标签并且有 1 条评论,那么它会告诉我有 3 条评论,而不仅仅是 1 条。

所以它向我显示(评论的编号)*(相关标签的编号)评论。

我该如何解决这个问题?

4

1 回答 1

1

使用COUNT(DISTINCT c.ID)代替COUNT(c.ID)

SELECT
    p.ID,
    p.title,
    p.body,
    p.c_date,
    GROUP_CONCAT(DISTINCT CONCAT_WS('|', 
                                    CAST(t.ID AS CHAR), 
                                    t.title) SEPARATOR ';') AS tags,
    COUNT(DISTINCT c.ID) AS comments
FROM Post p
    LEFT JOIN Comment  AS c  ON p.ID      = c.id_post
    LEFT JOIN Post_Tag AS pt ON p.ID      = pt.id_post
    LEFT JOIN Tag      AS  t ON pt.id_tag = t.ID
GROUP BY p.ID, 
         p.title, 
         p.body, 
         p.c_date;
ORDER BY p.c_date DESC
于 2013-05-23T07:28:42.183 回答