如何搞定这个复杂的查询?

时间:2013-05-23 07:26:55

标签: mysql sql database

这是我的数据库架构:

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.

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

如何解决此问题?

1 个答案:

答案 0 :(得分: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