代码之家  ›  专栏  ›  技术社区  ›  ranebec

计数时如何返回0而不是null?

  •  0
  • ranebec  · 技术社区  · 2 年前

    我有一个问题:

    with comments_info as (
            SELECT p.post_id as post_id,
                   COUNT(p.id) as comments
            FROM post_comments p
            GROUP BY post_id
        )
    select p.id as post_id, c.comments
    from posts p
                 left join comments_info c on c.post_id = p.id
    

    但如果帖子上没有评论,则count返回null。 我试着这样做:

    CASE WHEN COUNT(p.id) IS NULL THEN '0' ELSE COUNT(p.id) END as comments

    但它仍然返回null。

    注释模型:

     id pk,
    
     post_id fk,
    
     description text,
    

    Posts模型:

    id pk,
    title varchar,
    description text,
    
    2 回复  |  直到 2 年前
        1
  •  0
  •   A l w a y s S u n n y    2 年前

    COALESCE 通过包装您的计数, see

    COALESCE(count(p.id),0) as comments
    

    根据评论:

    使用 聚结 在外部查询中:

    COALESCE (p.comments, 0)
    
        2
  •  0
  •   Bohemian    2 年前

    使用 COALESCE 在外部查询中:

    -- with clause omitted
    select
      p.id as post_id,
      coalesce(c.comments, 0) as comments
    -- from, join omitted
    

    当帖子没有评论时,其计数将不为空;不会有行,因此左连接将为的所有列返回null comments_info

    coalesce() 返回其参数的第一个非空值。