【问题标题】:COUNT of joined records in WHERE statementWHERE 语句中连接记录的 COUNT 个
【发布时间】:2014-08-17 06:32:07
【问题描述】:

我有如下表格:

发帖:

id   status
1    0
2    1
3    1

评论:

id   post_id 
1    2
2    1
3    3
4    2

我想选择 status=0 的帖子或帖子有 cmets。我做了这个查询:

SELECT t.*, COUNT(cmt.id) as commentsCount FROM `post` `t` LEFT JOIN comment cmt ON (cmt.post_id = t.id) WHERE t.status='0' OR commentsCount>0 GROUP BY t.id 

但它不正确。

如何解决这个问题?

P.s 只有简化的表格可以让这更容易理解,在我的数据库中我无法添加带有计数的字段。

【问题讨论】:

    标签: sql join count where


    【解决方案1】:

    您需要将此条件放在having 子句中:

    SELECT t.*, COUNT(cmt.id) as commentsCount
    FROM `post` `t` LEFT JOIN 
          comment cmt
          ON (cmt.post_id = t.id)
    WHERE t.status = '0'
    GROUP BY t.id 
    HAVING commentsCount > 0;
    

    编辑:

    对于or 逻辑,您可以将两个条件移至having 子句:

    SELECT t.*, COUNT(cmt.id) as commentsCount
    FROM `post` `t` LEFT JOIN 
          comment cmt
          ON (cmt.post_id = t.id)
    GROUP BY t.id 
    HAVING max(t.status) = '0' OR commentsCount > 0;
    

    max() 严格来说是不必要的,因为id 是主键。但为了清楚起见,我将其包括在内。

    【讨论】:

    • 但帖子不一定有 cmets,但只有当 status 不为 '0' 时
    【解决方案2】:

    还有更直接的方法可以将您的查询从英语翻译成 SQL:

    SELECT *
    FROM post
    WHERE status='0'
      or (select count(1) from comment where post_id = post.id) > 0
    

    我建议您检查哪个查询对您的数据有更好的计划(使用联接或使用子查询)。无论如何,强烈建议您使用特殊字段进行过滤。

    【讨论】:

      【解决方案3】:

      在您的 group by 子句中,您将需要 select 子句中的所有字段,除了具有聚合函数的字段。所以您的查询将是:

      SELECT t.id, t.status, COUNT(cmt.id) as commentsCount FROM `post` `t` 
      LEFT JOIN comment cmt ON (cmt.post_id = t.id) 
      WHERE t.status='0' OR commentsCount>0 GROUP BY t.id, t.status
      

      此外,由于状态始终为零,您可能会将其从您的 select 和 group by 子句中排除。

      SELECT t.id, COUNT(cmt.id) as commentsCount FROM `post` `t` 
      LEFT JOIN comment cmt ON (cmt.post_id = t.id) 
      WHERE t.status='0' OR commentsCount>0 GROUP BY t.id
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-29
        • 2015-09-02
        • 1970-01-01
        • 2011-06-17
        • 2018-02-14
        • 1970-01-01
        • 2020-07-31
        • 1970-01-01
        相关资源
        最近更新 更多