【问题标题】:SQL Query INNER JOIN with three tablesSQL 查询 INNER JOIN 与三个表
【发布时间】:2013-02-24 17:37:51
【问题描述】:

有这三个表:

  1. 帖子
  2. posts_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 个点赞。

有什么帮助吗?

谢谢

【问题讨论】:

  • 左连接不是内连接。如果你想要它是否有匹配
  • 如果要从不匹配的表中获取行,则需要左连接或右连接,具体取决于要返回空记录的表在哪一侧。跨度>
  • 谢谢@tony-hopkinson 和 steoleary,你们是对的。

标签: mysql inner-join


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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-21
    • 2014-02-24
    • 2015-01-10
    • 2010-12-19
    • 2012-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多