Here are my tables's structures:
-- users
+----+--------+
| id | name |
+----+--------+
| 1 | Jack |
| 2 | Peter |
| 3 | Ali |
+----+--------+
-- reputations
+----+-------------+---------+-------+------------+------------+
| id | post_id | user_id | score | reputation | date_time |
+----+-------------+---------+-------+------------+------------+ -- Suppose:
| 1 | 1 | 1 | 1 | 5 | 1500489844 | -- out of last week
| 2 | 4 | 3 | -1 | -2 | 1500499815 | -- out of last week
| 3 | 2 | 3 | 1 | 5 | 1500584821 |
| 4 | 3 | 1 | 1 | 5 | 1501389166 |
| 5 | 2 | 4 | 1 | 5 | 1501399142 |
| 6 | 2 | 1 | -1 | -2 | 1501399142 |
| 7 | 4 | 1 | 0 | 15 | 1501481186 |
+----+-------------+---------+-------+------------+------------+
-- Note: the last row came from an accepted-answer, that's why its score is 0
-- post_tag
+---------+--------+
| post_id | tag_id |
+---------+--------+
| 1 | 2 |
| 1 | 4 |
| 2 | 2 |
| 3 | 1 |
| 3 | 4 |
| 4 | 3 |
+---------+--------+
-- tags
+----+--------+
| id | name |
+----+--------+
| 1 | php |
| 2 | html |
| 3 | css |
| 4 | mysql |
+----+--------+
-- post_category
+---------+-------------+
| post_id | category_id |
+---------+-------------+
| 1 | 2 |
| 2 | 3 |
| 3 | 1 |
| 4 | 2 |
| 5 | 1 |
| 6 | 2 |
| 7 | 1 |
+---------+-------------+
-- there is an unique index on post_id column. since each post can has only one category
-- categories
+----+------------+
| id | name |
+----+------------+
| 1 | social |
| 2 | technology |
| 3 | political |
+----+------------+
Now I want to get list of users with their reputations, scores, top two tags in last week. How can I do that?
Note1: "top tow tags" means the two tags that the user has earned more repo in them.
Note2: Each question has at least 1 tag.
Here is the expected output:
+----+--------+-------+------------+----------+------------+
| id | name | score | reputation | tags | category |
+----+--------+-------+------------+----------+------------+
| 1 | Jack | 0 | 18 | css,php | technology |
| 3 | Ali | 1 | 5 | html | political |
| 2 | Peter | 0 | 0 | NULL | NULL |
+----+--------+-------+------------+----------+------------+
-- Note: It's ordered by reputation, score columns
Here is what I've tried:
SELECT u.*,
sum(r.score) as score,
sum(r.reputation) as reputation
/* WS_CONCAT(',', t.name) as tags */
FROM users u
LEFT JOIN reputation r ON r.user_id = u.id
/* I need more joins to get tags, I don't know how exactly */
WHERE r.date_time > unix_timestamp(DATE_SUB(now(), INTERVAL 1 WEEK)
GROUP BY u.id
ORDER BY reputation, score
As you can see, my query lacks the last column (tags). Honestly, I don't know how I should manage such a thing. Do you know how?