mysql:在特定时间获取数据

时间:2014-03-06 12:28:21

标签: mysql

需要建议在1月31日23:59:59(月末)查找状态= 1的所有用户的列表。

select count(*) from users where status=1 and created_at=?

5 个答案:

答案 0 :(得分:0)

将数据库还原到以前的某种方法是将binlog反向运行到当前数据库状态。
或者
启动数据库模式并运行与仅与表相关的binlog中的所有语句。

如果Slave仍处于某个先前的状态

,请寻求Slave的帮助

答案 1 :(得分:0)

以下语法将为任何状态= 1且在2014年1月31日创建的用户提供

select count(*) 
from users 
where status=1 and DATE(created_at)='2014-01-31'

此语法将为具有确切时间'2014-01-31 23:59:59'的用户提供帮助。假设dateformat是相同的。似乎unlikley当时用户已创建。

select count(*) 
    from users 
    where status=1 and created_at='2014-01-31 23:59:59'

答案 2 :(得分:0)

select
count(*)
from 
users
where status=1 and 
created_at = concat(last_day(curdate(), ' 23:59:59'));
  • 详细了解last_day()函数here

答案 3 :(得分:0)

如果使用linux服务器,则通过cronjob安排以下脚本 -

在user.sh文件中保存以下行。

vi user.sh


#!/bin/bash

DBUSER=your_server_user
DBPASS=your_server_pass

mysql -u$DBUSER -p$DBPASS db_name -e "select count(*) from users where status=1;" >> user.xls

echo -e "Please get the attached user Report." | mail -s"user Report" -a user.xls abc@abc.com

现在cron这个脚本 -

crontab -e

59 23 31 1 * /script_path/user.sh

它将在23:59执行31,并将用户报告发送到您的邮件ID。

如果您使用的是Windows服务器,则可以创建批处理文件并在Windows任务计划的帮助下调用它。

答案 4 :(得分:0)

在评论中,您提到了一个存储历史用户更新的表。您可以使用此表来检查当时状态为1的用户:

SELECT COUNT(DISTINCT user_id) AS users
FROM status_history sh
WHERE
sh.created = (SELECT MAX(sx.created) 
                     FROM status_history sx
                     WHERE sx.user_id = sh.user_id
                     AND sx.created < '2014-01-31 23:59:59')
AND sh.status = 1

我们进行内部选择以获取每个状态和用户的最新状态更改日期,并获取该日期的历史记录。然后我们会计算任何状态为1的人。显然,如果您的表架构不同,您可能需要调整上述内容。

SQL Fiddle example