[英]SQL Query INNER JOIN with three tables
有以下三个表:
该查询返回了我的帖子,并且它们的回复都很好。 SELECT 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
该查询返回的“喜欢计数”很好,但不包括那些没有“喜欢”的记录。 因此此查询返回的记录是:40
我希望包括每个回复的“喜欢计数”,即使它有0个喜欢。
有什么帮助吗?
谢谢
使用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
仅在双方都有行时才起作用。 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.