简体   繁体   中英

mysql php : how to efficiently fetch previous X dates that include entries

Imagine a basic website where users post something on random dates. The system uses mysql-php and stores each post in a table, call tablePost, with a column storing the date (or time). Note that the user can post multiple posts in a day. What I want to achieve is to be able to fetch date of last 4 days (or even more) that user posted. Also the post information (postid, posttext etc) is to be fetched. An example output is:
- 2012-04-25 (3 posts, postinfo...)
- 2012-04-12 (2 posts, postinfo...)
- 2011-09-12 (33 posts, postinfo...)
- 2011-03-04 (10 posts, postinfo...)

I can imagine two solutions:

1) Use only tablePost table, iterate over entries by php and fetch required data

2) Create another table, call tableActiveDays. when a user posts, an entry (userId, dateDay) is inserted possibly with INSERT IGNORE or checking whether it has not been inserted before. Therefore, each (userId, dateDay) is unique. In this way, if I want to fetch last 4 active days, I can use a simple select ... order by ... limit by 4 query.

My questions are:
- Any other way to achieve this task ?
- What is the most efficient way to achieve this ?

Create INTEGER field and call it "dt_timestamp". When user post message save in "dt_timestamp" result of time() function.

UPDATE:
If you have registered users then add field with INTEGER type, call it last_activity . When user post something update this field with time() . Then use this query:

SELECT pt.* FROM post_table pt JOIN users_table ut ON ut.id = pt.user_id WHERE pt.dt_timestamp >= ut.last_activity - 86400 * 4 AND ut.id = %needed_user_id%;

users_table has field id - user's id. post_table has field user_id - field value from users_table.

Using DATETIME is much slower then just integer timestamp.

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