How can I count the number of posts?

后端 未结 3 1387
太阳男子
太阳男子 2021-01-29 03:37

Here is my table structure:

-- reputations
+----+-------------+---------+-------+------------+------------+
| id | post_id     | user_id | score | reputation | d         


        
相关标签:
3条回答
  • 2021-01-29 04:20

    I post this using mobile phone so I cannot try it on the fiddle you gave. I modify your SQL to count number of post using COUNT.

    SELECT
    t.tag, 
    sum(r.reputation) AS tag_reputation, 
    sum(r.score) AS tag_score,
    COUNT(DISTINCT pt.post_id) AS post_num
    FROM
    users u
    LEFT JOIN reputations r 
        ON r.user_id = u.id 
            AND r.date_time > 1500584821
    JOIN post_tag pt ON pt.post_id = r.post_id
    JOIN tags t ON t.id = pt.tag_id
    WHERE u.id = 1 -- Specific user: Jack
    GROUP BY
    u.id, u.user_name, t.tag 
    ORDER BY
    u.id, tag_reputation DESC;
    

    Edit: I add COUNT with DISTINCT. See if it solve.

    0 讨论(0)
  • 2021-01-29 04:23

    Some things about your expected results don't exactly line up - for example, your expected results include posts from before the date you excluded in your where clause, and the original query's results include results that aren't from user id = 1 so I am a bit confused overall but:

    I think just adding:

    SELECT
        t.tag, sum(r.reputation) AS tag_reputation, sum(r.score) AS tag_score, count(r.id) as post_num
    

    should make this work?

    If not, you can use a inline select in your select statement:

    SELECT
        t.tag, sum(r.reputation) AS tag_reputation, sum(r.score) AS tag_score, 
        max((select count(r2.id) from users u2 
            LEFT JOIN reputations r2 ON r2.user_id = u2.id AND r2.date_time > 1500584821 
            JOIN post_tag pt2 ON pt2.post_id = r2.post_id 
            JOIN tags t2 ON t2.id = pt2.tag_id 
            where t.tag = t2.tag)) AS post_num
    FROM
        users u
        LEFT JOIN reputations r 
        ON r.user_id = u.id 
            AND r.date_time > 1500584821
    JOIN post_tag pt ON pt.post_id = r.post_id
    JOIN tags t ON t.id = pt.tag_id
    WHERE u.id = 1 -- Specific user: Jack
    GROUP BY
        u.id, u.user_name, t.tag 
    ORDER BY
        u.id, tag_reputation DESC;
    
    0 讨论(0)
  • 2021-01-29 04:27

    Did you try adding the post id to the query?

    I added count(r.post_id) as post_num in your select statement and it gave the expected results.

    To remove duplicates, use distinct. Do you want the count with respect to tag table? Try

    1. COUNT(distinct pt.post_id) AS post_count; or
    2. COUNT(distinct r.post_id) AS post_count
    0 讨论(0)
提交回复
热议问题