2015-09-22 116 views
0

此查詢不選擇,無評論或無表決數據,我如何解決?3個表的mysql查詢

SELECT 
    blog_posts.*, 
    COUNT(DISTINCT(blog_comments.CommentID)) AS CountComments, 
    COUNT(DISTINCT(blog_votes.VoteID)) AS CountVotes, 
    AVG(DISTINCT(blog_votes.Vote)) AS AvgVote 
    FROM blog_posts 
    INNER JOIN blog_comments ON blog_comments.CommentBlogID=blog_posts.BlogID 
    INNER JOIN blog_votes ON blog_votes.VoteBlogID=blog_posts.BlogID 
    ORDER BY blog_posts.BlogID 
    LIMIT 0,10 
+0

'GROUP BY blog_post.col1,blog_posts.col_2,...' – lad2025

+0

所以你想計數評論,投票和平均投票數據? –

+0

@MichaelAntonio它的真實 –

回答

0

這個怎麼樣,我使用子查詢,使之簡單:

SELECT b.*, 
    COUNT(select CommentID from blog_comments where CommentBlogID = b.BlogID group by CommentID) as CountComments, 
    COUNT(select VoteID from blog_comments where VoteBlogID = b.BlogID group by VoteID) as CountVotes, 
    AVG(select Vote from blog_comments where VoteBlogID = b.BlogID group by Vote) as AvgVote, 
FROM blog_posts as b 
ORDER BY b.BlogID 
LIMIT 0,10 
+0

#1064 - 你的SQL語法有錯誤;請查看與您的MySQL服務器版本相對應的手冊,以便在'SELECT blog_comments.CommentID FROM blog_comments WHERE blog_com'的第3行 –

1

我固定

SELECT 
blog_posts.*, 
COUNT(VoteID) as CountVotes, 
AVG(VoteID) As AvgVotes, 
COUNT(CommentID) AS CountComments 
FROM blog_posts 
LEFT JOIN blog_votes ON blog_posts.BlogID = blog_votes.VoteBlogID 
LEFT JOIN blog_comments ON blog_posts.BlogID = blog_comments.CommentBlogID 
GROUP BY blog_posts.BlogID 
ORDER BY BlogID DESC 
LIMIT 0,10