简体   繁体   English

每月和每周的MySql时间戳查询和比较

[英]MySql timestamp query and comparison in monthly and weekly

i have a table where i enter entries for applicants. 我有一张表格,在其中输入申请人的条目。 it has a column date_added where the type is timestamp and the default is current_timestamp. 它具有date_added列,其类型为timestamp,默认值为current_timestamp。 i want to make a weekly and monthly report but i can't decide what would be the best thing to do. 我想做一个每周和每月的报告,但我不能决定什么是最好的事情。 i need an sql statement that return the number of entry like this.. 我需要一个返回这样的条目数的sql语句。

switch($searchby){
case "monthly": $qry = "select * from tblapplicant where date_added > $month"; break;
case "weekly": $qry = "select * from tblapplicant where date_added > $week"; break;
}

$res = mysql_query($select);
$rec_count = mysql_num_rows($res);

echo "There are <font color='red' size='3'>".$rec_count."</font> matching records found.";

i know this is incorrect but this is all i can think at the moment. 我知道这是不正确的,但这是我目前能想到的。

another thing i want is, i want it to be the exact year and month report.. 我想要的另一件事是,我希望它是确切的年度和月份报告。

edit: output should be: There are 13 applicants for the whole month of June 2013. - or if weekly - There are 3 applicants for the third quarter of July 2013. 编辑:输出应为:2013年6月整个月有13名申请人。-或每周一次-2013年7月第三季度有3名申请人。

I suggest the following approach. 我建议采用以下方法。 First, use your php code to determine the day that your search period begins, and the day after it ends. 首先,使用您的php代码来确定搜索期限的开始日期以及结束日期。 For example, if it's a monthtly report for September 2013, your start date would be 2013-09-01, and the end date would be 2013-10-01. 例如,如果它是2013年9月的月度报表,则您的开始日期为2013-09-01,结束日期为2013-10-01。 Then you simply have one query. 然后,您只需查询一个。

 where date_added >= $startdate
 and date_added < $enddate

The major benefits of this approach are: 这种方法的主要好处是:

  1. The time component of your timestamp field gets handled. 您的时间戳字段的时间部分得到处理。
  2. Your query will run reasonably quickly, especially if date_added is indexed. 您的查询将相当快地运行,尤其是在为date_added编制索引的情况下。
  3. It's easier to sort out programmnig logic with application code than with sql 与应用程序代码相比,使用应用程序代码对programmnig逻辑进行分类更容易
  4. You can write your query as a stored procedure to make it even faster. 您可以将查询作为存储过程编写,以使其更快。

This can be your sql statement 这可以是你的sql语句

select * from tblapplicant where month(date_added) > $month
select * from tblapplicant where DAYOFWEEK(date_added) = X

You should replace X whith your weeek day 1 = Sunday, 2 = Monday, …, 7 = Saturday 您应该将X替换为您的第1周=星期日,2 =星期一,…,7 =星期六

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

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