Here is my table structure:
-- reputations
+----+-------------+---------+-------+------------+------------+
| id | post_id | user_id | score | reputation | d
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.
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;
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
COUNT(distinct pt.post_id) AS post_count
; or COUNT(distinct r.post_id) AS post_count