每天对数据库中的数据进行编码点火器查询


Codeigniter query to data from database for each day

我有一个$from date$to date,所以我想从数据库中获取四个值,$from$to之间的几天,包括$from$to。如果数据在数据库中不存在一天,则必须将零作为缺失值的值。

那么我将如何在编码点火器中编写查询以使其发生,并且相应的日期应存储在特定行的结果中。

我以前的解决方案是使用 PHP 检查并设置缺少日期的零。但是我有一些新的解决方案,您可以尝试

  1. 创建表以存储日期以及与表的左/右连接
  2. 或者使用存储过程和连接创建临时表。会话过期时将自动删除临时
  3. 将 UNION 与 select 语句一起使用

关于StackOverflow有很多答案MySQL如何填写范围内的缺失日期?MySQL 按日期和计数分组,包括缺少的日期超过日期范围的总计 - 填写缺失的日期MySQL在使用GROUP BY DATE(table.timestamp)时填写缺失的日期,而不加入临时表

我认为您的解决方案实际上需要在PHP中,并且不确定您是否可以通过查询直接从MYSQL获得所需的内容。据我了解,您要运行查询,获取您定义的日期范围内的所有记录,然后让没有记录的日期具有空行(或您决定的任何其他值......

我实际上会运行与选择日期范围之间的行相同的查询,并使用 DatePeriod 类生成开始日期和结束日期之间所有天的数组。

$begin = new DateTime( '2012-08-01' );
$end = new DateTime( '2012-10-31' );
$end = $end->modify( '+1 day' );
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);
foreach($daterange as $date){
    echo $date->format("Y-m-d") . "<br>";
}

有了这个,我们将能够每天从$from_date跑到$end_date

接下来,我们需要从数据库中转到其他行,并根据我们拥有的daterange对象查看哪些天有记录,哪些天没有记录。

我相信这是一种可行的方法,它不是最干净的样本,而是一些额外的工作,你可以让它更漂亮一点,但我认为这将适用于你需要的东西。

代码中的数据库部分不在 Codeigniter 中,但由于它只获取一个简单的查询,因此更改它应该没有任何问题。

// set the start & end dates
$from_date = '2012-09-11';
$to_date     = '2012-11-11';
// create a daterange object
$begin         = new DateTime($from_date);
$end           = new DateTime($to_date );
$end            = $end->modify( '+1 day' );
$interval      = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);
$sth = $dbh->prepare("SELECT col1, dateCol from tb WHERE dateCol>'".$from_date."' AND dateCol<'".$to_date."' order by dateCol ");
$sth->execute(); 
$rows = $sth->fetchAll(PDO::FETCH_ASSOC);
$rowsByDay = array(); // will hold the rows with date keys
// loop on results to create thenew rowsByDay
foreach($rows as $key=>$row) {
    $rowsByDay[strtotime($row['dateCol'])][] = $row; // add the row to the new rows array with a timestamp key
}
// loop of the daterange elements and fill the rows array 
foreach($daterange as $date){
    if(!isset($rowsByDay[strtotime($date->format("Y-m-d"))])) // if element does not exists - meaning no record for a specific day
    {
        $rowsByDay[strtotime($date->format("Y-m-d"))] = array(); // add an empty arra (or anything else)
    }
}
// sort the rowsByDay array so they all are arrange by day from start day to end day
ksort($rowsByDay); 

// just for showing what we get at the end for rowsByDay array
foreach ($rowsByDay as $k=>$v) {
    echo date('Y-m-d',$k);
    var_dump($v);
    echo '<hr/>';
}

希望这能让你走上正确的道路...

希望这有帮助,

$this->db->where('date_column >= ',$date_given_start);
$this->db->where('date_column <= ',$date_given_end);
$this->db->get('TABLE_NAME')->result();

// if column is datetime
$this->db->where('DATE(date_column) >= ',$date_given_start);
$this->db->where('DATE(date_column) <= ',$date_given_end);
$this->db->get('TABLE_NAME')->result();