简体   繁体   English

mysql php:如何有效地获取包含条目的先前X日期

[英]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). 系统使用mysql-php并将每个帖子存储在一个表中,称为tablePost,其中一列存储日期(或时间)。 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. 我想要实现的是能够获取用户发布的最近4天(甚至更多)的日期。 Also the post information (postid, posttext etc) is to be fetched. 还要获取帖子信息(postid,posttext等)。 An example output is: 示例输出为:
- 2012-04-25 (3 posts, postinfo...) -2012-04-25(3个帖子,postinfo ...)
- 2012-04-12 (2 posts, postinfo...) -2012-04-12(2个帖子,postinfo ...)
- 2011-09-12 (33 posts, postinfo...) -2011-09-12(33个帖子,postinfo ...)
- 2011-03-04 (10 posts, postinfo...) -2011-03-04(10个帖子,postinfo ...)

I can imagine two solutions: 我可以想象两个解决方案:

1) Use only tablePost table, iterate over entries by php and fetch required data 1)仅使用tablePost表,通过php遍历条目并获取所需数据

2) Create another table, call tableActiveDays. 2)创建另一个表,调用tableActiveDays。 when a user posts, an entry (userId, dateDay) is inserted possibly with INSERT IGNORE or checking whether it has not been inserted before. 用户发布时,可能会使用INSERT IGNORE插入条目(userId,dateDay),或者检查是否之前未插入过条目。 Therefore, each (userId, dateDay) is unique. 因此,每个(userId,dateDay)都是唯一的。 In this way, if I want to fetch last 4 active days, I can use a simple select ... order by ... limit by 4 query. 这样,如果我想获取最近4个工作日,我可以使用简单的select ... order by ... limit by 4查询。

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". 创建INTEGER字段,并将其称为“ dt_timestamp”。 When user post message save in "dt_timestamp" result of time() function. 当用户发布消息保存在time()函数的“ dt_timestamp”结果中time()

UPDATE: 更新:
If you have registered users then add field with INTEGER type, call it last_activity . 如果您已经注册了用户,则添加INTEGER类型的字段,将其称为last_activity When user post something update this field with time() . 用户发布内容时,请使用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%; 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. users_table有场id -用户的ID。 post_table has field user_id - field value from users_table. post_table具有字段user_id -users_table中的字段值。

Using DATETIME is much slower then just integer timestamp. 使用DATETIME比使用整数时间戳要慢得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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