2015-01-17 86 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。 –

相關問題