0

有这三个表:

  1. 帖子
  2. post_replies
  3. 喜欢

这个查询正在返回我的帖子,他们的回复都很好。选择posts.title,posts.num,posts.status,posts.category,posts.content,posts.member_num,COUNT(posts_replies.blyrb_num)AS计数

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 很好,但不包括那些没有 Likes 的记录。所以这个查询返回的记录是:40

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

有什么帮助吗?

谢谢

4

1 回答 1

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仅在双方都有行时才有效。:)

于 2013-02-24T17:42:11.563 回答