简体   繁体   中英

Count number of post and total like per user in a range of time in MySQL

I have 2 tables: members and posts

In table members , I have USERID for each user. In table posts , I have PID for each post and USERID of the user who created the post. Each post also has number_of_like , indicating how many times a post was liked.

/*Table: posts*/
----------------

Field              Type              Null    Key     Default         Extra          
-----------------  ----------------  ------  ------  ----------  --------------
PID                bigint(20)        NO      PRI     (NULL)      auto_increment
USERID             bigint(20)        NO              0                         
number_of_like     int(10) unsigned  YES             0                         
number_of_comment  int(10) unsigned  YES             0                         
date_added         date              NO              0000-00-00

Now I want to count that: in a range of time (DATE(date_added) > CURDATE() - INTERVAL 30 DAY) , each user have how many posts and the total like of them. I count by month and week.

Can I do that directly in a query? Or must I use foreach to count for each user, write it to a stats table and then SELECT from stats when needed?

Any help is really appreciated. Thank you :)

UPDATE

I need to list all users, regardless of their post count.

Yes, this can be done. Try something like this:

SELECT 
    U.USERID,
    COUNT(*),                <- total of posts per user
    SUM(A.number_of_like)    <- total of likes in these posts
FROM users U
LEFT JOIN posts A ON U.USERID = A.USERID
WHERE ISNULL(A.USERID) 
    OR A.date_added > DATE_ADD(CURDATE(), INTERVAL -30 DAY)
GROUP BY A.USERID;

I've used DATE_ADD for the date calculation, other date functions might be possible here, too.

Update:

After you've provided the detail you want every user (not only the ones that have posts), I've updated the SQL query above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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