2015-01-17 89 views
0

我有4个表格:'num_of_cmt'是4而不是2。为什么?

users(id,name,email);

id | name | email 
1 | ABC  | [email protected] 
2 | XYZ  | [email protected] 
3 | AAA  | [email protected] 

论文(ID,标题,内容,CREATED_BY)

id | title    | content    | created_by 
1 | This is title 1  | This is content 1 | 1 
2 | This is title 2  | This is content 2 | 1 
3 | This is title 3  | This is content 3 | 3 
4 | This is title 4  | This is content 4 | 1 
5 | This is title 5  | This is content 5 | 3 
6 | This is title 6  | This is content 6 | 2 

评级(ID,paperId,明星)

id | paperId  | star 
1 | 1   | 2 
2 | 2   | 4 
3 | 3   | 4 
4 | 2   | 2 
5 | 1   | 3 

评论(ID,paperId,味精)

id | paperId  | msg 
1 | 1   | abcd 
2 | 2   | xxxx 
3 | 2   | yyyy 
4 | 3   | zzzz 
5 | 1   | tttt 
6 | 4   | kkkk 

我想领域:papers.id,papers.ti TLE,papers.content,users.name, AVG(rating.star),COUNT(comments.msg)

我执行一个查询,如:

SELECT papers.id, papers.title, papers.content, users.name, 
AVG(rating.star) AS avg_star , COUNT(comments.msg) AS num_of_cmt 
FROM papers 
JOIN users ON users.id = papers.created_by 
LEFT JOIN rating ON rating.paperId = papers.id 
LEFT JOIN comments ON comments.paperId = papers.id  
WHERE papers.id = 1 

然后结果是在 “num_of_cmt” 假字段:

id title    content   name  avg_star num_of_cmt 
1 This is title 1  This is content 1 ABC  2.5000  4 

上面'num_of_cmt'是4而不是2。为什么?

+1

和你一样加入一张表的方式不同,除了你做了四次。如果您希望我们解决您的实际问题,请将其放入标题中,而不是询问如何加入四张表格(因为这是一个非常不同的问题,而不是您在帖子正文中提出的问题)。 –

+1

如果显示所有字段,您将看到重复的行。这是因为连接是跨产品操作。您可以使用嵌套查询和分组获取正确的计数,而不是实际计数的倍数。 – Schien

+1

通过paperId对组评分和评论,然后聚合然后加入。 –

回答

2

对于paperid = 1ratingscomments都有多行。因此,连接表产生四个结果,与以下ID:

ratings comments 
    1   1 
    1   5 
    5   1 
    5   5 

因此,计数为4。您可以通过执行count(distinct comments.id)修复计数。然而,平均水平会下降。

解决此问题的一种方法是在子查询中汇总ratingscomments

+0

问题解决了。谢谢@Gordon Linoff。 –

相关问题