有这三个表:
此查询返回我的帖子,他们的回复计数都很好。
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 <>3
AND posts.access = 'Public'
AND (
posts.title LIKE '%dress%'
OR posts.content LIKE '%dress%'
)
GROUP BY posts.num
但问题是这个查询只返回有回复的帖子。我不想要这样的限制,我想要所有帖子是否有回复。
关于我在这里做错了什么想法?
谢谢
答案 0 :(得分:2)
在“FROM”和第一个“JOIN”中交换表格,并将第一个“JOIN”更改为LEFT 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
LEFT JOIN posts_replies ON ( posts_replies.blyrb_num = posts.num )
LEFT JOIN likes ON ( likes.comment_num = posts_replies.num )
WHERE posts.status <>3
AND posts.access = 'Public'
AND (
posts.title LIKE '%dress%'
OR posts.content LIKE '%dress%'
)
GROUP BY posts.num
答案 1 :(得分:1)
要做的事情:
LEFT JOIN
代替INNER JOIN
POST
和posts_replies
查询,
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
LEFT JOIN posts_replies
ON ( posts_replies.blyrb_num = posts.num )
LEFT JOIN likes
ON ( likes.comment_num = posts_replies.num )
WHERE posts.status <> 3 AND
posts.access = 'Public'
AND
(
posts.title LIKE '%dress%'
OR posts.content LIKE '%dress%'
)
GROUP BY posts.num