简体   繁体   中英

mysql query to select all rows of current month?

我有一个名称为startdate的列名为datetime类型。我必须获取当前月份的开始日期和结束日期之间的所有行。这是从1 / nov / 2014到2014年11月30日。

select * from your_table
where year(curdate()) = year(startdate)
and month(curdate()) = month(startdate)

要查找当月的所有记录,请使用以下简单的一行代码:

SELECT * FROM `Your_Table` WHERE MONTH(startdate) = MONTH(CURDATE());

The most efficient way is to do all the date arithmetic on the current date. Here is one method:

select t.*
from table t
where t.date >= date(now()) - interval day(date(now()) + 1 day and
      t.date < (date(now()) - interval day(date(now()) + 1 day) + interval 1 month 

The complex date arithmetic calculates the first day of this month and the first day of the next month. This formulation allows MySQL to take advantage of an index on the date column.

要在日期之间获取数据:

SELECT * FROM table1 WHERE dateColumn BETWEEN STR_TO_DATE('2014-11-01', '%Y-%m-%d') AND STR_TO_DATE('2014-11-30', '%Y-%m-%d');

For selecting day or week or month records use this function:

 function get_records_by_period($period, $your_date) {
if ($period == 'today') {
    $timeSQL = ' Date($your_date)= CURDATE()';
}
if ($period == 'week') {
    $timeSQL = ' YEARWEEK($your_date)= YEARWEEK(CURDATE())';
}
if ($period == 'month') {
    $timeSQL = ' Year($your_date)=Year(CURDATE()) AND Month(`your_date`)= Month(CURDATE())';
}

$Sql = "SELECT * FROM your_table WHERE ".$timeSQL
return $Result = $this->db->query($Sql)->result_array();
}

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