简体   繁体   English

SQL 查询未在 SUM 和 COUNT 中找到所有行

[英]SQL Query not finding all rows in SUM and COUNT

select coalesce(ratings.positive,0) as positive,coalesce(ratings.negative,0) as negative,articles.id,x.username,commentnumb, 
    articles.category,
    articles."createdAt",
    articles.id,
    articles.title,
    articles."updatedAt"
    FROM articles
    LEFT JOIN (SELECT id AS userId,username,about FROM users) x ON articles.user_id = x.userId
    LEFT JOIN (SELECT id,
        article_id,
        sum(case when rating = '1' then 1 else 0 end) as positive,
        sum(case when rating = '0' then 1 else 0 end) as negative
        from article_ratings
        GROUP by id
        ) as ratings ON ratings.article_id = articles.id
    LEFT JOIN (SELECT article_id,id,
       count(article_id) as commentNumb
       from article_comments
       GROUP by id
       ) as comments ON comments.article_id = articles.id
    WHERE articles."createdAt" <= :date
    group by ratings.positive,ratings.negative,articles.id,x.username,commentnumb
    order by articles."createdAt" desc
    LIMIT 10

The code is working, however I have many more comments and many more ratings than what is counted in both SUM and COUNT functions.代码正在运行,但是我的评论和评分比 SUM 和 COUNT 函数中计算的要多得多。

How do I fix this query?如何修复此查询?

This is using postgres.这是使用 postgres。

I've done some experimentation and it seems that the third join for comments is the one causing issues.我做了一些实验,似乎第三个评论加入是引起问题的一个。

In the derived tables, you should ideally be grouping using article_id.在派生表中,理想情况下您应该使用 article_id 进行分组。 But, you are grouping based on id.但是,您是根据 id 分组的。 Due to this, you are getting more than the necessary rows in the derived tables.因此,您在派生表中获得的行数超过了必要的行数。 I have modified the query to suit your needs.我已修改查询以满足您的需要。

    SELECT COALESCE(ratings.positive,0) AS positive,COALESCE(ratings.negative,0) AS negative,articles.id,x.username,commentnumb, 
        articles.category,
        articles."createdAt",
        articles.id,
        articles.title,
        articles."updatedAt"
        FROM articles
        LEFT OUTER JOIN (SELECT id AS userId,username,about FROM users) x ON articles.user_id = x.userId
        LEFT OUTER JOIN (SELECT article_id,
            SUM(case when rating = '1' then 1 else 0 end) as positive,
            SUM(case when rating = '0' then 1 else 0 end) as negative
            FROM article_ratings
            GROUP by article_id 
            ) AS ratings ON ratings.article_id = articles.id
        LEFT OUTER JOIN (SELECT article_id,
           count(article_id) as commentNumb
           FROM article_comments
           GROUP by article_id
           ) AS comments ON comments.article_id = articles.id
        WHERE articles."createdAt" <= :date
        ORDER BY articles."createdAt" desc
        LIMIT 10;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM