MySQL:简单查询修改

时间:2013-03-03 08:50:39

标签: mysql

有这三个表:

  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, 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
    

    但问题是这个查询只返回有回复的帖子。我不想要这样的限制,我想要所有帖子是否有回复。

    关于我在这里做错了什么想法?

    谢谢

2 个答案:

答案 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
  • 交换表:POSTposts_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