插入帐户MYSQL查询的年龄

时间:2016-03-02 16:02:24

标签: php mysql codeigniter insert datediff

start_dateaccount_add_date两个日期找到差异然后插入名为account_age的列中的最佳方法是什么?

我需要的是让用户选择start_date表示其1月份。

然后他们添加account_add_date的日期说三月。

差异为2个月,因此account_age为2,

然后在4月那个2将是3月5日,6月5日等等

任何人都知道怎么做?

我当前的插入查询模型

 function create_bank()
{
    $this->load->helper('date');

    $new_bank_acc_insert_data = array(
        'bank_name' => $this->input->post('bank_name'),
        'interest' => ($this->input->post('interest') / 100),
        'start_amount' => $this->input->post('start_amount'),
        'length' => $this->input->post('length'),
        'start_date' => date('Y-m-d',strtotime($this->input->post('start_date'))),
        'mem_id' => $this->session->userdata('id'),
        'account_add_date' => $this->current_date()
    );

    $insert = $this->db->insert('bank', $new_bank_acc_insert_data);
    return $insert;
}

查找帐户年龄的想法

SELECT DATEDIFF('start_date','account_add_date')

1 个答案:

答案 0 :(得分:2)

SELECT     
(
   12* (YEAR(account_add_date) - YEAR(start_date)) + 
          (MONTH(account_add_date) - MONTH(start_date))
) AS differenceInMonth
FROM
YOUR_TABLE

虽然DATEDIFF函数返回两天中的差异,但与月份差异相比更准确

<强>解释

示例:

start_date = 2014 March

account_add_date = 2015 January

YEAR(account_add_date) = 2015

YEAR(start_date) = 2014

MONTH(account_add_date) = 1

MONTH(start_date) = 3

So according to the query:

12 * (2015-2014) + (1-3) = 12 * 1 - 2 = 10 (Months)