SQL Query INNER JOIN有三个表

时间:2013-02-24 17:37:51

标签: mysql inner-join

有这三个表:

  1. 帖子
  2. posts_replies
  3. 喜欢
  4. 此查询返回我的帖子,他们的回复计数都很好。 SELECT posts.title,posts.num,posts.status,posts.category,posts.content,posts.member_num,COUNT(posts_replies.blyrb_num)AS count

    FROM posts_replies
    INNER JOIN posts ON ( posts_replies.blyrb_num = posts.num )
    WHERE posts.status =1
    AND posts.access = 'Public'
    GROUP BY posts.num
    ORDER BY count DESC
    LIMIT 50 
    

    记录此查询返回的是:47

    这是一个有点更新的查询,我想在帖子上提取每个回复的喜欢计数。

    SELECT posts.title, posts.num, posts.status, posts.category, posts.content, posts.member_num, 
    COUNT( posts_replies.blyrb_num ) AS count,
    COUNT( likes.comment_num  ) AS likes_count
    FROM posts_replies
    INNER JOIN posts ON ( posts_replies.blyrb_num = posts.num )
    INNER JOIN likes ON ( likes.comment_num = posts_replies.num )
    WHERE posts.status =1
    AND posts.access = 'Public'
    GROUP BY posts.num
    ORDER BY count DESC
    LIMIT 50 
    

    此查询返回Likes Count,但不包括那些没有喜欢的记录。 所以此查询返回的记录是:40

    我想包括每个回复的喜欢计数,即使它有0个喜欢。

    任何帮助?

    谢谢

1 个答案:

答案 0 :(得分:1)

使用LEFT JOIN代替INNER JOIN可能会对您有所帮助

SELECT posts.title, posts.num, posts.status, posts.category,
posts.content,posts.member_num, 
COUNT( posts_replies.blyrb_num ) AS count,
COUNT( likes.comment_num  ) AS likes_count
FROM posts_replies
INNER JOIN posts ON ( posts_replies.blyrb_num = posts.num )
LEFT JOIN likes ON ( likes.comment_num = posts_replies.num )
WHERE posts.status = 1
AND posts.access = 'Public'
GROUP BY posts.num
ORDER BY count DESC
LIMIT 50 

LEFT JOIN的想法是匹配行,即使在右侧没有匹配也是如此。 INNER JOIN仅在双方都有行时才有效。 :)

相关问题