根据蛋糕php中的日期将mysql行拆分成多行

时间:2015-03-09 03:45:43

标签: php mysql arrays cakephp cakephp-2.0

我的数据如下表所示 -

enter image description here

但我想根据日期将mysql行拆分成多行

enter image description here

因为我想计算两个日期之间发送电子邮件的数量,如下面的代码 -

$condition[] = array(
                'LeadTime.send ' => 1
                'DATE(LeadTime.date) >= ' =>   $this->request->data['from_date'],
                'DATE(LeadTime.date) <= ' =>   $this->request->data['end_date'],
                );
}
$count = $this->Time->find('count', array(
                             'conditions' => $condition,
                              ));
pr($count);

如果UNION表数据基于日期列或直接我可以在cake php中实现它,我不会先获得。

请指导我。

1 个答案:

答案 0 :(得分:0)

这是一个基于表设计计算结果的SQL语句。

SELECT  SUM(IF(first_send = 1 
                 AND first_start_date BETWEEN from_date AND end_date
                 AND second_send = 1 
                 AND second_start_date BETWEEN from_date AND end_date
             ,2,1)) as amount
FROM times
WHERE 
  (first_send = 1 AND first_start_date BETWEEN from_date AND end_date)
  OR 
  (second_send = 1 AND second_start_date BETWEEN from_date AND end_date);

在Cakephp中实现:您可能应该使用prepared statement,因为在创建列时停止sql注入会很困难。

$db = $this->Time->getDataSource();
$db->fetchAll(
    'SELECT  SUM(IF(first_send = 1 
                 AND first_start_date BETWEEN ? AND ?
                 AND second_send = 1 
                 AND second_start_date BETWEEN ? AND ?
             ,2,1)) as amount
     FROM times
     WHERE 
      (first_send = 1 AND first_start_date BETWEEN ? AND ?)
       OR 
      (second_send = 1 AND second_start_date BETWEEN ? AND ?)',
  array($this->request->data['from_date'],$this->request->data['end_date']
       ,$this->request->data['from_date'],$this->request->data['end_date']
       ,$this->request->data['from_date'],$this->request->data['end_date']
       ,$this->request->data['from_date'],$this->request->data['end_date']));

使用find的难度/问题是阻止sql注入,如下面的代码所示。

$this->Time->virtualFields['amount'] = 'SUM(IF(first_send = 1 
                 AND first_start_date BETWEEN' . $this->request->data['from_date'] . ' AND ' . $this->request->data['end_date']
                 . ' AND second_send = 1 '
                 . ' AND second_start_date BETWEEN ' . $this->request->data['from_date'] . ' AND ' . $this->request->data['end_date']
                 . ',2,1))';

$conditions = array('OR' =>(
    array('AND'=>array('Time.first_send' => '1'
                      ,'Time.first_start_date BETWEEN ? AND ?' => 
                          array($this->request->data['from_date']
                               ,$this->request->data['end_date']))),
    array('AND'=>array('Time.second_send' => '1'
                      ,'Time.second_start_date BETWEEN ? AND ?' => 
                          array($this->request->data['from_date']
                               ,$this->request->data['end_date'])))
  ));

$this->Time->find('all',array(
    'conditions' => $conditions,
    'fields' => array('amount'),
    ));