【问题标题】:Mysql query to search posts and comments, return total comment countMysql查询搜索帖子和评论,返回总评论数
【发布时间】:2021-03-14 00:23:40
【问题描述】:

我正在尝试编写一个查询

  1. 在表格 Posts 和 Comments 中搜索字符串
  2. 如果任一表上存在匹配项,则返回匹配的帖子及其总评论数。

我有:

SELECT Posts.id, Comments.id, Count(DISTINCT Comments.id)
FROM Posts 
LEFT JOIN Comments ON Comments.postid = Posts.id 
WHERE ( Posts.text LIKE '%test%' 
          OR ( Comments.text LIKE '%test%'  
          AND Comments.deleted = false ) ) 
       AND Posts.approved = true 
       AND Posts.deleted = false 
GROUP BY Posts.id

这个查询的问题是 where 过滤了我的 Comments.id 计数,因此它不是返回帖子中的 cmets 总数,而是返回匹配“test”的 cmets 数量。 如何在单个查询中实现我想要的?

【问题讨论】:

  • 请描述逻辑。您的查询比您描述的要多。
  • 发布一个示例数据,其中包含您获得的当前输出和您的预期输出。

标签: mysql sql


【解决方案1】:

如果我理解正确,您希望所有帖子或评论都包含感兴趣的字符串。对于匹配的,您需要总评论数。

为此,使用having

SELECT p.id, Count(c.id)
FROM Posts p JOIN
     Comments c
     ON c.postid = p.id 
GROUP BY p.id
WHERE p.approved = true AND
      p.deleted = false 
HAVING p.text LIKE '%test%' OR
       SUM( c.text LIKE '%test%' AND c.deleted = false ) > 0;
      

【讨论】:

  • 这不起作用。没有加入?否 And between Where 条件?
  • 无法让它工作,你正确理解了我的问题。
  • @david987 。 . .你遇到了什么问题?
【解决方案2】:

其实GROUP BY子句是不需要的:

SELECT Posts.id, 
    ( SELECT COUNT(*) FROM Comments c 
      WHERE c.postid = Posts.id AND c.deleted = false
    ) AS total_post_comments
FROM Posts 
WHERE Posts.approved = true 
    AND Posts.deleted = false 
    AND (
        Posts.text LIKE '%test%'
        OR EXISTS(
            SELECT 1 FROM Comments
            WHERE Comments.text LIKE '%test%'
              AND Comments.deleted = false
              AND Comments.postid = Posts.id
        )
    )

【讨论】:

  • 这行得通!我很好奇是否有办法在没有子查询的情况下做到这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多